Which is a better way of using the image as link - javascript

Which is the better way of using the image as a link..
<A HREF="javascript:password()">
<IMG SRC="pict1.gif" NAME="pic1" ALT="about us!" BORDER="0" align="left"></A>
or the same thing using onClick in the img tag ??
Which one is advisable?? Are both equally good to use??

I'll chime in with the rest that you should always take a semantic approach. Looking at the value of href, though, it seems that you're not actually linking to anything, but rather, your a tag is performing an action.
In that case, your using an anchor as though it was a button, and the semantics is lost anyhow. I'd go with an image button:
<input type="image" src="pict1.gif" onclick="password();" />
One example of why you want to care about semantics (except for the general SEO reasons) is that you're instructing the browser as to what is going on. For instance, an image button as in the code above, or an image in an anchor as in your question, will both cause the image to have the pointer cursor when hovered, whereas you'd have to explicitly style that behavior if you went with the plain img onclick solution, effectively replicating something the browser can handle natively.

There are three common techniques:
a with href="javascript:whatever()"
a with href="#" onclick="whatever(); return false;"
img with onclick="whatever()"
(1) and (2) will create a dotted focus border around the image when its clicked, sometimes this is undesirable.
(1) and (2) adds a border around the image same color as the links in your document so you may want to set border=0.
(1) and (2) will display the hand pointer upon mouse over.
(3) does not behave anything like a link... no focus border, no link color borderm no hand pointer, nothing displayed in the status bar upon mouseover.
Personally, I'd go for option 3: use an a tag for links that take you somewhere, do not use them as action buttons.

I'm a fan of good semantics. the <a> was designed to be a link so i advise to use it :D

For accessibility you should use the anchor tag. You can style it to display an image ie
<style>
a.image {display:block; background-image: url('images/mypic.gif')}
</style>
<a class='image' href='acme.html' style=></a>
(That might need a width and height as well)
In addition, jQuery will provide a true separation of concerns should you need to add further processing in the click. (Please no flames about the OP not using jquery, I present it here as an approach since the question is slightly subjective and about best practices)
$(document).ready(function() {
$(a.image).click(function(e) {
password();
e.preventDefault();
});
});

Using an a-tag, you can make the code work if the user doesn't have javascript enabled! So I would go for the a tag, but also keep in mind that you could use jQuery or similar to get the javascript effect when clicking on the link.

I'd go with an anchor (A tag) barring a really good reason to do something else. Linking is what anchors are for, and so you get accessibility benefits, etc.

I discourage both approaches. Logic, presentation and structure should always be separate. Do this instead:
myClickable.addEventListener('click', password, false);

if its merely a link then anchor would work well for you, but button will be better in case you have some operation to be done and not only redirection.

Related

Anchor tag display full link issue

I found some really awesome link detection regex that works unbelievably great. It takes only the main part of a link and displays it as the body of the anchor tag and the whole link as the href. In example http://somesite.com/index.php?some=var will simply look like somesite.com. Which is just pure awesomeness, but then again it has its down side as well because someone might pass some variables that you might not necessarily want to send for some reason and I figured I need to display the whole url in the anchor body. Sadly I don't want to just give up on beautiful anchors and I decided I should display full link upon some event and thus came the trouble.
First I thought I should go for mouse hover (jquery's mouseenter) to display full link and then use mouseleave to make it beautiful again. Unfortunately that was unsuccessful due to short site names at the end of a line with a bunch of parameters. Example: If there is an anchor with body site.com and href http://site.com/some/params at the end of a line, after expanding it will go to the next line which would trigger the mouse leave and thus compressing it, which would by it self return the link to the original line and trigger the expand function creating an infinite loop.
Second idea was to have a right-click expand the link. Obviously the context menu on links that are to be expanded has to be disabled. Unfortunately, again, having the same link at the end of a line would cause a context menu to show up because after expanding the right click is also triggered at the blank space where the short link used to be.
I seem to have run out of ideas, does anyone have any?
Without breaking layout, you can use the native title property to display the full URL or, for something more customizable, a plugin such as jQuery UI's tooltip widget.
<a href="http://www.shorturl.com/?param=notSoShortUrl"
title="http://www.shorturl.com/?param=notSoShortUrl">shorturl.com</a>
Provided the title attribute is outputted in the initial markup, this solution works even with JS disabled. And if you feel like, jQuery UI tooltip may help customizing it for JS-enabled users.
If anyone is interested in how to patch the line-breaking issue described in the OP, here's my original solution to achieve non-line-breaking extensible links:
aaaaaaaaaaaaaaaaaa.com
$('a').hover(function(e) {
$(this).text(e.type == 'mouseenter' ? this.href : $(this).data('shorturl'));
}).each(function() {
$(this).css({
width: this.offsetWidth,
whiteSpace: 'nowrap',
display: 'inline-block'
}).data('shorturl', $(this).text());
});
Demo
Though, this is mostly a CSS hack and link text may leak outside of the container (and obviously, won't work if the container has overflow:hidden), so it is not very good for layout purposes. Better stick with title or the tooltip plugin.

How is it better to make a button?

I want to add a 'fancy' button to my page. I see two possibilities:
an a element with a picture as background and add a javascript function to the click event.
or
an img element and add a javascript function to the click event.
What is your opinion ? Which one is the better way to do it and why ?
Thank you !
Other options include:
A link that styled to look like a button using a background image
A Button element that is styled with a background image and no border.
An Input element with type submit or button styled with a background image and no border.
I find that that button element works the best, particularly if you want rollover hover effects.
jQuery UI has a button plug-in that will style pretty much any kind of interactive element into a fancy button.
Wherever possible, UI elements should be defined as CSS backgrounds. They are not part of the site content, so they don't really need to be indexed by search engines.
Semantically-speaking an A-tag implies a link, and therefore the event should be hooked up to the A-tag, not the image.
The first one. You have more options to style it, and it's easier to "theme" it as well. Imaging a "dark theme" and a "light theme", using CSS you can easily keep the same HTML but have totally different styles and images for your button. In some browsers, images are not necessary; you can easily create your button using pure CSS.
It depends on what you're trying to do.
On my project, we have a form that we want to submit using a button rather than javascript, so we're inserting a button element.
<button type="submit">Sign Out</button>
Then you can style the button using CSS.
Other than that, we use images for non-form buttons and javascript for the functionality behind them.
Not sure what you mean by 'fancy' button but first look into what you're able to do with CSS, look for example at http://hellohappy.org/css3-buttons/ or http://twitter.github.com/bootstrap/base-css.html#buttons .
If you want something fancier than that you should define a link in HTML, with and anchor tag since that's semantically correct and set it's background to an image with CSS. I don't see any reason to use Javascript for the click event as long as you simply want to make A GET request to some other page.
Semantically, <button> and <input type="button|submit|reset" /> elements are the correct choice for interactive elements within the page.
If you're simply styling a link to look like a button, then continue to use an <a> element, but define some styles and use a class, such as <a class="button">.
Pretty much any element can be made into a button, and if you use the correct attributes it will maintain semantics.
The following are semantically identical, but the <img> requires JS support:
<!-- the image is of some fanciful text -->
<img src="some/image.jpg" alt="Continue" role="button" tabindex="0" />
<input type="image" src="some/image.jpg" alt="Continue" />
If you simply have a decorative image that doesn't affect the content, you could use a span or div that's styled with CSS:
<span role="button" tabindex="0" class="button continue-button">Continue</span>
I'm pretty sure you can get that effect with plain CSS, no need for JS unless you want to call a function of some sort, and to spazz the button there is no need for a JS function.
You can simply use CSS actions (not sure they are named this way) like active, hover, focus, etc...
here is an example:
http://jsfiddle.net/RQucV/2/
it has a red color for background at first, changes to blue while clicking and becomes purple when visited. this is possible because i used a 'a' tag which has these properties.
i only changed the background color, but you can also changes many other elements, such as font, background image, margins, borders, you name it.
i think its cleaner to use pure CSS because of the JS clutter. if you want to add more scripts later, something bad is bound to happen when the browser has too much scripting to do. besides, parsing CSS might actually be faster than JS.
Just another tip if you go with pure CSS: not all browsers handle CSS the sameway, i highly recommend appending a "reset.css" to your stylesheet in order to make it play along the sameway in every browser you use.
hope it helps!

Is it good practice (or a good idea) to leave out HREF on links that are hooked up via JavaScript?

Expanding on this question,
For items that trigger dialogs and menus (i.e. non navigational), is it good practice to leave out the HREF attribute in links that have events that are hooked up via JavaScript? In these cases, does it makes sense to have HREF there at all?
From this: some text
Or even worse, this: some text (which forces you to use event.preventDefault())
to this: <a>some text</a>
==Edited a little more==
Bad, bad idea. It wont show up as a link for one thing. If you need a button, but are use an <a> as one, just using a <button> or <input type="button">. As you said, "non-navigational". The entire point of <a> is navigational.
Out of those two tho, use href="#" putting javascript:// in a link is worse than adding inline styles.
Pragmatically - this is what I have learned over 16 years of JS
have the href, if not you need to set the cursor to hand or pointer
make the href go to a "sorry you need javascript" page if you do not want to use # or as I learned recently #somethingNotExisting
NEVER have href="javascript:anything()"
return false or preventDefault in the onclick which is preferably set in an onload handler
UPDATE: For menus and such, the agreed markup are lists with css and using links in such menus is recommended if the links actually loads content to gracefully degrade to plain html navigation if script is off
You should use the command element instead.
The command element represents a command that the user can invoke.
HTML5: Edition for Web Authors
This has the benefit of being semantically correct. There's at least one fork of html5shiv which 'enables' support for the element in older browsers.

How do I create a "widget" for people? It's just a simple text box with my logo

I want something that the webmaster can copy into his site.
It just needs to have my logo, a text box, and a submit button. (When the user clicks submit using that widget, it forwards to my site.)
I know there are many ways to do this. What is the fastest and easiest?
I don't know about fastest and easiest, but maybe you could write a little JavaScript file that creates and injects the content into a div with a special ID.
This is along the lines of what StackOverflow does for their "flair."
Fastest way is to just put some HTML code that people can paste in their page. There's no need for buttons or form, just a simple link.
Something on the lines of:
<a href="http://www.yoursite.com/">
<img src="http://www.yoursite.com/yourlogo.jpg" alt="yoursite.com logo" title="Visit yoursite.com!" />
</a>
You'll probably want to add a couple of style tags (e.g to avoid borders around the image etc)
Also, it would be easy on your site to have a little JS that changes the code above so that people can personalize it (point to different images, different sizes etc etc)
Some may frown upon it but possibly the fastest and easiest way is to use an iframe. It means that the embed code can be quite short + you can change the behaviour at a later date.
Iframe's main advantage is that you don't have to deal with the css that's already included in the page. Might not seem like a big deal but sooner or later you'll run into a page that does something with a css attribute that you just hadn't expected.
It's not pretty but it's worth considering.

Why is it bad practice to use links with the javascript: "protocol"?

In the 1990s, there was a fashion to put Javascript code directly into <a> href attributes, like this:
Press me!
And then suddenly I stopped to see it. They were all replaced by things like:
Press me!
For a link whose sole purpose is to trigger Javascript code, and has no real href target, why is it encouraged to use the onclick property instead of the href property?
The execution context is different, to see this, try these links instead:
Press me! <!-- result: undefined -->
Press me! <!-- result: A -->
javascript: is executed in the global context, not as a method of the element, which is usually want you want. In most cases you're doing something with or in relation to the element you acted on, better to execute it in that context.
Also, it's just much cleaner, though I wouldn't use in-line script at all. Check out any framework for handling these things in a much cleaner way. Example in jQuery:
$('a').click(function() { alert(this.tagName); });
Actually, both methods are considered obsolete. Developers are instead encouraged to separate all JavaScript in an external JS file in order to separate logic and code from genuine markup
http://www.alistapart.com/articles/behavioralseparation
http://en.wikipedia.org/wiki/Unobtrusive_JavaScript
The reason for this is that it creates code that is easier to maintain and debug, and it also promotes web standards and accessibility. Think of it like this: Looking at your example, what if you had hundreds of links like that on a page and needed to change out the alert behavior for some other function using external JS references, you'd only need to change a single event binding in one JS file as opposed to copying and pasting a bunch of code over and over again or doing a find-and-replace.
Couple of reasons:
Bad code practice:
The HREF tag is to indicate that there is a hyperlink reference to another location. By using the same tag for a javascript function which is not actually taking the user anywhere is bad programming practice.
SEO problems:
I think web crawlers use the HREF tag to crawl throughout the web site & link all the connected parts. By putting in javascript, we break this functionality.
Breaks accessibility:
I think some screen readers will not be able to execute the javascript & might not know how to deal with the javascript while they expect a hyperlink. User will expect to see a link in the browser status bar on hover of the link while they will see a string like: "javascript:" which might confuse them etc.
You are still in 1990's:
The mainstream advice is to have your javascript in a seperate file & not mingle with the HTML of the page as was done in 1990's.
HTH.
I open lots of links in new tabs - only to see javascript:void(0). So you annoy me, as well as yourself (because Google will see the same thing).
Another reason (also mentioned by others) is that different languages should be separated into different documents. Why? Well,
Mixed languages aren't well supported
by most IDEs and validators.
Embedding CSS and JS into HTML pages
(or anything else for that matter)
pretty much destroys opportunities to
have the embedded language checked for correctness
statically. Sometimes, the embedding language as well.
(A PHP or ASP document isn't valid HTML.)
You don't want syntax
errors or inconsistencies to show up
only at runtime.
Another reason is to have a cleaner separation between
the kinds of things you need to
specify: HTML for content, CSS for
layout, JS usually for more layout
and look-and-feel. These don't map
one to one: you usually want to apply
layout to whole categories of
content elements (hence CSS) and look and feel as well
(hence jQuery). They may be changed at different
times that the content elements are changed (in fact
the content is often generated on the fly) and by
different people. So it makes sense to keep them in
separate documents as well.
Using the javascript: protocol affects accessibility, and also hurts how SEO friendly your page is.
Take note that HTML stands for Hypter Text something something... Hyper Text denotes text with links and references in it, which is what an anchor element <a> is used for.
When you use the javascript: 'protocol' you're misusing the anchor element. Since you're misusing the <a> element, things like the Google Bot and the Jaws Screen reader will have trouble 'understanding' your page, since they don't care much about your JS but care plenty about the Hyper Text ML, taking special note of the anchor hrefs.
It also affects the usability of your page when a user who does not have JavaScript enabled visits your page; you're breaking the expected functionality and behavior of links for those users. It will look like a link, but it won't act like a link because it uses the javascript protocol.
You might think "but how many people have JavaScript disabled nowadays?" but I like to phrase that idea more along the lines of "How many potential customers am I willing to turn away just because of a checkbox in their browser settings?"
It boils down to how href is an HTML attribute, and as such it belongs to your site's information, not its behavior. The JavaScript defines the behavior, but your never want it to interfere with the data/information. The epitome of this idea would be the external JavaScript file; not using onclick as an attribute, but instead as an event handler in your JavaScript file.
Short Answer: Inline Javascript is bad for the reasons that inline CSS is bad.
The worst problem is probably that it breaks expected functionality.
For example, as others has pointed out, open in new window/tab = dead link = annoyed/confused users.
I always try to use onclick instead, and add something to the URL-hash of the page to indicate the desired function to trigger and add a check at pageload to check the hash and trigger the function.
This way you get the same behavior for clicks, new tab/window and even bookmarked/sent links, and things don't get to wacky if JS is off.
In other words, something like this (very simplified):
For the link:
onclick = "doStuff()"
href = "#dostuff"
For the page:
onLoad = if(hash="dostuff") doStuff();
Also, as long as we're talking about deprecation and semantics, it's probably worth pointing out that '</a>' doesn't mean 'clickable' - it means 'anchor,' and implies a link to another page. So it would make sense to use that tag to switch to a different 'view' in your application, but not to perform a computation. The fact that you don't have a URL in your href attribute should be a sign that you shouldn't be using an anchor tag.
You can, alternately, assign a click event action to nearly any html element - maybe an <h1>, an <img>, or a <p> would be more appropriate? At any rate, as other people have mentioned, add another attribute (an 'id' perhaps) that javascript can use as a 'hook' (document.getElementById) to get to the element and assign an onclick. That way you can keep your content (HTML) presentation (CSS) and interactivity (JavaScript) separated. And the world won't end.
I typically have a landing page called "EnableJavascript.htm" that has a big message on it saying "Javascript must be enabled for this feature to work". And then I setup my anchor tags like this...
<a href="EnableJavascript.htm" onclick="funcName(); return false;">
This way, the anchor has a legitimate destination that will get overwritten by your Javascript functionality whenever possible. This will degrade gracefully. Although, now a days, I generally build web sites with complete functionality before I decide to sprinkle some Javascript into the mix (which all together eliminates the need for anchors like this).
Using onclick attribute directly in the markup is a whole other topic, but I would recommend an unobtrusive approach with a library like jQuery.
I think it has to do with what the user sees in the status bar. Typically applications should be built for failover in case javascript isn't enabled however this isn't always the case.
With all the spamming that is going on people are getting smarter and when an email looks 'phishy' more and more people are looking at the status bar to see where the link will actually take them.
Remember to add 'return false;' to the end of your link so the page doesn't jump to the top on the user (unless that's the behaviour you are looking for).

Categories

Resources