Should I use on click instead of href? - javascript

I have few items in my navigation bar side and horizontal. Each item holds the link for different page. I have read few articles about href attributes. There is a lot of different opinions on what should be used especially in HTML5 since href is not required. I would like to hide the link if possible. One of the options is to use onClick function. Also there is big debate on if there should be javascript or # sign. For example:
Option 1
or Option 2
<a href="javascript:void(0);" onclick="someFunction(e)">
I was wondering if this is the best way to approach this. Also I saw few options where JQuery is involved but I'm not sure if that would be the best option. if anyone can help with this please let me know. I just want to use something that is well tested and will be a long term solution. Thanks in advance.

If you are actually linking to another HTML page with a URL... then use a link element and an href.
If you are in some framework and changing a route or view - or triggering some event - it's up to you. You can use buttons or any element or an <a> if you want, but you have a ensure to prevent the default behaviour of the link.
It sounds like your question is not between href or none - but between link or something else.
regular link
<a href='http://sheriffderek.consulting' target='sheriff'>link</a>
A fallback link for non-javascript sites? (not likely in 2017 unless you are a public library or something)...
<a href='http://sheriffderek.consulting' onclick='someFunction(e)'>js view trigger with fallback link</a>
another element
<button onclick="someFunction(e)">button</button>
Also - it depends on the framework. I believe Angular just says to use a link but leave off the href.

Nowadays, I see most of the developers prefer "#" to "javascript:".
If I had to use onclick, I'd personally do it like this:
Link
Another example:
Link
<script>
someFunction = function(event) {
event.preventDefault();
// do the work
}
</script>
To answer one of your concerns, showing links in the page shouldn't be a security concern. Each server request must be protected against unauthorized calls, URL obfuscation will not help almost at all.

The method you use to redirect the page (or invoke an event) really depends on what you are trying to achieve from the action and the overall user experience. There are cases where an href is more appropriate:
An image that is also a link
A word or phrase that is used as a link
An actual link you want displayed to the user
An onClick event of a button can be coded to achieve the same effect but with a different route. Perhaps the code will be more efficient or the User Experience is improved with a button click event than just an href.
The two main things to keep in mind are the user experience and design and then the security of the page. Always ensure that any link/redirection will never compromise the security of the page. This could potentially determine the method you need to use.
For additional info, you can start by reading the following link and then continuing through the rest of the stack exchange UX section of the site:
I hope it helps a little.
Action in href or onClick event?

Related

href="javascript:;" or href="javascript:void(0)", the difference?

I read about the href="#" and href="javascript:void(0)"comparison,
I also want to know about the comparison about
href="javascript:;" or href="javascript:void(0)",
ps: I use href="javascript:;" all the time instead of href="javascript:void(0)",
have not find any trouble.
Using javascript: in hyperlinks in either form is bad. Your JavaScript design should be unobtrusive.
If you're going to attach event listeners to your anchors, you should use the # anchor or even an actual URL, e.g.:
delete
...
<script>
jQuery(function($) {
$('a').on('click', function(event) {
event.preventDefault();
// do ajax stuff
});
});
</script>
This way, old browsers (or those with JavaScript disabled) will follow a regular link to delete an item whereas JavaScript enabled browsers will do this via AJAX so that the page doesn't have to refresh.
If your link is really meant to do nothing at all, you shouldn't use anchors at all; just style a <span> for that purpose.
What you put in the href is not really relevant. You should stop the link from being followed in the first place, by returning false from the click handler.
Example:
<a href="fallback.html" onclick="doSomething();return false;">
In the href you can put a link to a fallback solution for users who have disabled Javascript, or a page informing them that they need Javascript to use the featured of the page.
javascript:void(0) - more easy to understand, than javascript:some_code_to_execute. Sure, in your case javascript:; is not hard to read, is one will not assume code got broken.
Theres several reason, why handling lcicks with javascript: is bad. I know it's not the actual question, but it's related:
This approach is obsolete and as it still supported by browser vendors, it's not in wc3 standards.
Link href="javascript" will not work for users without javascript. It's better to use href="/somePage.com?id=123" onclick="makeActionFor(777); return false">
No separation between the markup and the code. In this case, putting onclick in prev example is also a bad way to attach click handler.
The usual behaviour for a javascript: link is that the document body is replaced with whatever the expression evaluates to, unless it evaluates to undefined. There is no difference between your two versions, they both evaluate to undefined which, in a javascript: link, has no effect.
However, this is not the preferred way of making no-op links. Your needlessly forcing the browser to parse and evaluate JavaScript. If you want to make a link which does nothing, you should be setting its href to "#", and binding functions to the link's click event. Your event handler will be passed an event object; if you want to evaluate some code and then prevent the link from being followed (appending # to the currently URL) then you can use event.preventDefault(), event.stopPropagation(), or simply return false from your event handler.
The best option of all is to maintain some meaningful value in your href attribute, so that if JavaScript is circumvented (IE, the user opens the link in a new window) there is still some sane fall-back. You should then layer additional "rich" actions on top of the existing HTML-only functionality.

Using button rather than a link for single page web app

I'm creating a web app that has a list of commands that change elements on a single page. The page is 100% dependant on JavaScript. I therefore coded these links as:
Command #1
Doubting that this is semantically correct, I found numerous places stating that I should use a button instead.
This makes sense, but means I have to alter the style of a button to look like a link, which feels hacky. Is this the correct method?
The style you give to the element is irrelevant to whether or not it's semantically correct code, so I wouldn't worry too much about that.
Links are meant to, well, link the user between pages on the web.
HTML Input elements are meant to take user input and do things with them.
Based on this simple heuristic, I'd say go with a button!
The HTML5 spec is pretty clear in that you shouldn't use a:
If the a element has an href attribute, then it represents a hyperlink (a hypertext anchor).
The definition of "hyperlink" is:
These are links to other resources […]
So don't use a for "actions" on your single page web app.
You should go with button or resp. input (I'd say both with type value of button).
If you like to dive into newer HTML5 stuff, take a look at menu and command.
Just to be sure: you shouldn't "enhance" other elements (like span or div) with JS to act like links/buttons. This wouldn't be accessible without further work, if at all.
Both are technically fine to use. For me, if it is a text link, then I'd use the <a> tag and if it is a form button or image, use <button>. That way you are consistent with what the elements intended uses are.
I don't think using links is semantically incorrect. If it makes you feel better, you can style your links as buttons.
Otherwise, if that still rubs you the wrong way, there's nothing wrong with styling a button to look like a link. The functionality of your app should have little to do with how you present your buttons, as long as they do the same thing and fit within your expectations.
As mentioned in the comments, if you wish to use buttons, bear in mind that they style as form elements and can be more difficult that working with an anchor tag.
Generally i prefer using div's for these things. Links come with a lot of inherent browser styling, even more so for buttons. Div's only rule is display:block. So it's saves me some reset css lines. Also it saves me some js code to prevent default behaviour. Add that to the fact that there is no correct semantic choice, then using div's makes a lot of sense.

Javascript Only Anchor - better to use a span?

I have an anchor tag in my application that has the sole purpose of firing some javascript to expand/collapse some panels. I was thinking about changing it to be a span with a click handler instead. Which is the best method:
Toggle Panels
OR
<a onclick="togglePanels()" href="javascript:void(0);">Toggle Panels</a>
OR
<span onclick="togglePanels()">Toggle Panels</span>
Or is there a better option that I have not included?
I would use a <button>. You can style it accordingly with CSS, but the semantic meaning is still preserved.
But if the user disables JavaScript, the button becomes useless and users might get confused.
If your site works with JavaScript only anyway, then this would be ok, but if it also works without, you better add it programmatically or hide it initially with CSS.
Update:
Don't forget to set type="button". By default a button is a submit button for a form, so omitting the type attribute would make it some kind of invalid outside of a form (although it would still work).
A common progressive-enhancement approach is to make your anchor an actual anchor link... if JS is not available, clicking the link will just bring the panels (which you can place down below, in the flow of the document, and hide on dom-ready/load when JS is available) to the top.
Toggle Panels
<div id="panels"><!-- your panels--></div>
Then in your click handler for #panelToggler, first use e.preventDefault() so it won't try to pull the anchor to the top, then include the logic to toggle the panels.
If you don't care about users without JS being able to use whatever is in the panels, then don't even show them the toggle panels control at all. Even if it doesn't look like a link, it is really janky to just have a non-working "toggle panels" line of text sitting there in your UI. In this case, it really doesn't much matter what element you hang the functionality on for the JS-enabled users... button is appropriate, but a is generally more flexible with styling options. Take a look at most of the buttons in GMail... they're clusters of nested divs.
I prefer to define a span element without any handler attributes, and then wire up any handlers in a separate script file. In my case, I have many different span elements with the same toggle expansion behavior, so giving them all the same class, like "expand", allows me to wire them all in my document loaded method using a class selector.
The better option would be using unobtrusive JavaScript:
var element = document.getElementById("#anchorId");
element.onclick = togglePanels;
A jQuery approach also helps a lot:
$("a").click(togglePanels);
But of course I think that it's nice as an anchor, since you can still have an href pointing to something in case the user isn't with JavaScript enabled.
Yes, if the element is in your original markup, the span is better. This is in the interest of some semblance of graceful degradation; users who don't have JavaScript enabled will still get the impression they can interact with the hyperlink, which they cannot.
The truly idealized unobtrusive solution would be to not include the element in the markup at all, and add it programmatically using JavaScript.
At the very least, you should not use the javascript: protocol in a hyperlink reference. Aside from challenges some might make that it is an improper use of hypertext references (hyperlinks should reference documents or resources, not define behavior) it poses a few technical challenges; for example, you don't have access to the anchor element via this.
I learned that a anchor will make the browser "ready to launch" when focused. Meaning some resurses will used. But I think transparency is important: http://www.javascripttoolbox.com/bestpractices/#onclick
Mike

Which is the best way to call a javascript function on a link

I want to add some links to some website of mine, but these links will call a javascript function and will not be underlined, also I want the cursor to be changed to a standard pointer. Which is the best way of doing it and why?
Right now I can think of two aproaches:
LINK
or
<span onClick="someFunction();" style="cursor: pointer;">LINK</span>
Which one do you think is better?
Since this isn't really going to be a link (functionally or visually) you should stick with a <span> (or <div> if you want a block level element).
"The HTML <span> tag is used for grouping and applying styles to inline elements. When the text is hooked in a span element you can add styles to the content, or manipulate the content with for example JavaScript." -W3
"The <a> tag defines a hyperlink, which is used to link from one page to another." -W3
If you're only calling a function I would use span.
I like v2, just because I would rather not have javascript functions in the url bar. What happens when they click the v1 link, and then bookmark?
I think a combination is better:
LINK
$(document).ready({
$('#myLink').click(function() { someFunction(); return false; });
});
If possible try putting a real URL in the href. By including a real href in the link you're allowing people to either experience the javascript version of your link (such as an ajax refresh) or right click and go to the real destination.
Of course this isn't always practical, your site might require that the action only be completed through a popup dialog. Ideally though the user should be open a link in another window/tab by following the href.

Anchored AJAX and SEO workaround?

You all know how to build AJAX sites with those 300ms trigger for checking anchors (hash links) in URL and then loading proper page with AJAX. But, these anchor links are nothing to search engines =(
I've thought of making some kind of workaround. All JS code remains the same, but, this little thing (I'm with JQuery, sorry):
$('a').live("click",function(){
var lnk = $(this).attr("href");
document.location.hash = lnk;
return false;
})
And then, you replace your anchor links in the body with plain links, build corresponding plain pages (still containing all JS codes) for non-javascript users and search engines. For normal visitors you would have plain links converted into hashes on fly and AJAX content loaded immediately. For those who are trying to load certain pages found through search engine - they will, and after that visitor will continue to move around with ajax navigation... somehow (remember, those plain direct pages still contain JS code).
I just want to make sure my assumptions are right. Are they?
Update: Bad thing is that when user directly enters some internal page with for ex. /portfolio address, he would then continue to /portfolio#contacts or similar URLs that are not so pretty, but still working (I mean /portfolio#contacts would show contacts).
That doesn't seem to be a good approach mainly because you'll end up having that function being triggered for the click event of each and every link, even those where you do not want to use your AJAX approach for loading content, for instance links to other sites or to javascript:....
If you place all your AJAX-y links under the same class or use another attribute to distinguish them and then adapt the jQuery selector that you're using there, then it will work and it will be a good approach because not only will it be SEO-friendly, but it also provides graceful degradation, that is, your users will still be able to access the content even if they're running in an environment where no JavaScript is allowed.
Other than that, and if SEO is your only concern, you may search the web for what a sitemap.xml file is and how to use it. Wikipedia has an article on it that may be worth a reading.
Sounds very sound... only I would suggest the callback on your 300ms timer also be called inside the event you have above, that way you have an instant result when clicking a link(and also a user can goto the link in the address bar and get the same effect)
Hey mate, you probably want to check out jQuery Ajaxy. It gracefully upgrades websites into rich ajax applications, so your website still works for SEO and Javascript disabled users.
You can see this functionality in action in this upcoming website. Notice how all the links are the same as they would be if the website isn't a Ajax application - and they still work if you right click and go open in new window!
This functionality is explained in detail at it's demo page. You can also find other examples and usage instructions there to:
http://www.balupton.com/sandbox/jquery-ajaxy/demo/
Overall to use it is surprisingly simple and straightforward (especially considering what it allows you to do!), and the support is fantastic.

Categories

Resources