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.
Related
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?
I've noticied the DOMSubtreeModified event is being deprecated (which is sad news), but I was wondering if there's a way to detect a change in every single tag on a page (I know - this can be really costly, but it has its purpose).
Basically, I want to know whenever an <a> tag (node) is created/modified so I can quickly scan its .href and see if it matches a pattern I'm looking for (if it is, I want to redirect it to run my JS (irrelevant to this) instead of navigating to said link). I need this to be generic (I don't know IDs/divs/anything except that they're <a href>s, and they have a specific URL pattern I'm looking for.
I know the support for this even is patchy but right now it'd only be used as a Chrome extension (Firefox to come soon after, so I'd have to tinker with it), so it should be okay for now.
Let me know if there are extra questions. Thanks!
You can catch the link action when it happens instead. What is the pattern you are looking for? It's just a matter of "selecting" the right <a>s. jQuery has attribute selectors for just about any occasion, "starts with", "ends with", "contains", "equals", etc...
$('a[href="http://notHere.com"]').on('click',function(event){
alert("omg don't go there!");
//window.location="http://www.goHere.com";
event.preventDefault();
});
jsFiddle
As per comment:
If your page will be changed dynamically you will need to delegate the event binding to something which will definitely always exist, and contain you target.
$('body').on('click','a[href="http://notHere.com"]',function(event){
alert("omg don't go there!");
//window.location="http://www.goHere.com";
event.preventDefault();
});
This puts the click handler on the <body> and from there it watches for clicks on the appropriate anchors. If you can get closer, go for it, eg: $('#mainContent')
I inherited some code with <img src="../...gif" onclick="aURL">.
I was wondering the reason behind this choice so I would like to know any potential advantages/disadvantages of window.location over a tag with href?
I am considering changing to <img src="../...gif">.
Thanks,
The main disadvantage with the <img onclick=""> approach I immediately see is that various forms of clicks will not work, e.g. Ctrl+click opening in a new tab, Shift+click opening in a new window, etc.
Also, JavaScript being disabled is also an area the onclick="window.location=x;" fails.
Definitely use an anchor here like you're thinking, that's its purpose.
As for the reason, I can't speak to that.
Typically, you're always better off setting the href on an anchor, even if you don't intend to use it. The href should be set as a fallback in case the user doesn't have JavaScript enabled, or if a bot is crawling your site and won't use the onclick event. If you have to open a popup, then put that in the onclick and return false so it doesn't hit the href. I would definitely recommend removing the onclick from the <img> and putting it in an <a> wrapping it.
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
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.