href="javascript:void(0)" vs. advanced disabling of links - javascript

I use
href="javascript:void(0)"
to disable the href property and then use onlclick to give functionality to my anchor elements. How can I do this programatically.

A few issues if I may.
I would suggest an unobtrusive approach
I would not use return false. It could have unexpected results. A quick google search will have more info.
Use preventDefault() to remove the default functionality.
https://developer.mozilla.org/en/DOM/event.preventDefault
Edit:
If you're unsure how to control the click event unobtrusively, addEventListener() is what you are after. You can control everything from there, including preventDefault()
https://developer.mozilla.org/en/DOM/element.addEventListener

Not sure what you mean when you say "works in xhtml, but not in javascript."
If you want to disable a link you can just use return false to cancel the default action.
Apple
Update - in context of a function
My Page
My Page
<script>
function myFunction() {
//do all the javascript stuff i want
return false;
}
function myFunction2() {
//do all the javascript stuff i want
}
</script>

Don't put javascript in href. Leave the href alone. Do what you want in onclick, just make sure it returns false (so that default link action isn't executed). And remember that people opening the link in new tab/window won't get your code executed - they'll just open the link under href.
If it doesn't make sense to have a href at all, you can also have onclick on any other element, not just a.

Related

Use a link ONLY when javascript is disabled

I have a social networking site for my college community and its working fine. There is a feature to like a post by other users. Liking is triggered using javascript's onClick() function.
Recently due to security reasons, many of our members disabled javascript.
Is there any way to redirect a user to a particular page if javascript is disabled? Otherwise the script should work.
For a more discriptive detail, assume my current code is like:
Item
what i want is something like:
Like
**but href should be active only if onclick() function dont work. is that possible? **
my site is built with php codeigniter. any solutions?
Just return false on the function that is called in the onClick event.
So either make sure that likeFunction() returns false. Or, return false afterwards with onClick="likeFunction(); return false;".
In general, you should always put a link in the href and not rely exclusively on JS. An anchor tag should not be abused with the onclick event to create pseudo-buttons. You might consider using a button tag if no link has to be put in the href.
Also, the href should start with the protocol (http://www.example.com instead of www.example.com).
Side note: You might consider attaching the JS event by calling addEventListener instead of using the onClick attribute. There are different cons and pros using either methods. I suggest you to have a look at this answer: addEventListener vs onclick.
Edit: As WillardSolutions suggested, you can use preventDefault to ensure the link is not opened when the onClick event is called. For further details, I suggest you to have a look at this answer: event.preventDefault() vs. return false
Don't muddy up your HTML, simply enhance it with JavaScript (see: Progressive Enhancement). This can be easily achieved with a CSS class and a document selector.
Given the HTML:
Like
You can add a self executing JavaScript function just before the </body> tag:
<script>
(function() {
document.querySelectorAll('a.like').forEach(function(item) {
item.removeAttribute('href');
item.onclick = function() {
/* add the likeFunction functionality here */
};
});
})();
</script>
That's pretty basic; it loops through all <a> tags that have class="like", removes the href attribute and adds the functionality from your current likeFunction() to the click event (if you copy the code from the likeFunction() to where indicated).
Obviously if JavaScript is disabled, the DOM isn't updated and your original HTML remains in place.
Note: forEach() support may be sketchy in Microsoft browsers.
Why not just use preventDefault()
// if js is disabled, this doesn't execute at all,
// so the link will work by default and take the user to the url defined inside the `href` tag.
document.getElementById('myLink').addEventListener('click', function(e) {
e.preventDefault(); // This will tell the browser not to follow the link.
... Do Awesome stuff here all day long
});
DEMO

How to execute onClick and href both in an anchor tag (<a>)

I have a link as follows:
Click me
On clicking the link, it's executing the JavaScript function, but it is not taking me to the href link.
How can I achieve the same?
I think the easiest way to do it is to make your function return true, so that after the function is complete, the anchor tag will behave like it normally does. This way you can also use the target-attribute if you want to use new window:
function myFunction() {
alert("hello");
return true;
}
Click me
I used jQuery, and I hope it's still understandable:
<a href="www.google.com" onClick=someFunction()>Click me </a>
It's executing the JavaScript function, but it is not taking me to the href link.
So one way is to add the redirection after your function:
function someFunction()
{
... Your code ...
window.location.href($(this).attr('href')); // <----- HERE
}
UPDATE AFTER COMMENT:
function someFunction()
{
... Your code ...
window.open($(this).attr('href'), '_blank'); // <----- HERE
}
You could do this a few ways,
<div onclick = "function();">link here </div>
or you could just use onclick on the a itself
link here
You're putting the onclick inside of the tags which is just for text. Place it in the first to use it as an attribute of the tag.
As Esko posted, in the function return true if you want the href to execute as well.
When the click event is attached on an anchor tag, it is handled by browser in a 'special' way.
The .click is not supposed to work with 'a' tags, because the browser does not support "fake clicking" with JavaScript.
I mean, you can't "click" an element with JavaScript. With 'a' tags you can trigger its onClick event, but the link won't change colors (to the visited link color, the default is purple in most browsers).
So it wouldn't make sense to make the "click" event work with 'a' tags since the act of going to the href attribute is not a part of the onClick event, but hardcoded in the browser.
But you can do some customization to an onclick handler so as to refer href link.
Let's have an example for it:
$('a').click(function () {
window.open($(this).attr('href'));
});
Here is the http://jsfiddle.net/4Qku8/ demonstrating the same using jQuery.
For further details, please refer to Stack Overflow question Can I call jQuery's click() to follow an link if I haven't bound an event handler to it with bind or click already?.

stopping the right click and go to link function for a tag

I have a tag like below. The question I have is how do I make this <a/> tag not behave like a link when user right clicks it. Since on a regular click the onclick event will fire and return false I am good with the regular click on the link the issue comes when a user right clicks the mouse and then gets the option like open in new tab or open in new window I have to prevent this from happening. I found out I can use javascript:void(0) in the href to do that but for some reason I cannot change the href as it is used for some other stuff. Is there any even or something that I can use.
<A title="Test1" onclick="javascript:search1('search'); return false;"href="team">search</A>
Thanks
as often, there's no universal solution, every browser do it its way. HTML 5 says form.oncontextmenu event handler should be supported. So this
<script>
document.oncontextmenu=function("alert('dont play with sources');return false");
</script>
should work if you use HTML 5.
you can also remove the javascript word, onclick already waits for js code (as oncontextmenu does).
<a onclick="search1('....

What is the best way to execute a function when user clicks on a link?

From my experience I know three different ways to execute a JavaScript function when a user clicks on a link
Use the onclick attribute on the link
click me
Use the href on the link
click me
Don't touch the link, do everything in js
click me
(in the JavaScript we will stop the default event, and call the function)
Which one is better? What are the advantages and disadvantages?
EDIT deleted the "javascript:" on onclick
Unobtrusive Javascript (your third example) with graceful degredation is the best choice.
It is always good to have a link in the href attribute so as to support users who have disabled JavaScript on their browsers.
click me
None of the above. Use the click event (assigned either as an attribute or via script if you prefer) and have a real URL as a fallback:
click me
or HTML:
click me
Script:
document.getElementById("myLink").onclick = function() {
myfunction();
return false;
};
Also, don't prefix code in event handler attributes with javascript:. It's incorrect and only doesn't throw an error by coincidence (which is that in JavaScript, javascript: creates a label called javascript).
Or alternatively, use jQuery
$(function() {
$('[id$=myLinkID]').click(function(e) {
myFunction();
});
});

"javascript:void(0);" vs "return false" vs "preventDefault()"

When I want some link to not do anything but only respond to javascript actions what's the best way to avoid the link scrolling to the top edge of the page ?
I know several ways of doing it, they all seem to work fine :
Hello
or
<a id="hello" href="#">Hello</a>
<script type="text/javascript>
$(document).ready(function() {
$("#toto").click(function(){
//...
return false;
});
});
</script>
and even :
<a id="hello" href="#">Hello</a>
<script type="text/javascript>
$(document).ready(function() {
$("#toto").click(function(event){
event.preventDefault();
//...
});
});
</script>
Do you have any preference ? why ? in which conditions ?
PS: of course the above examples assume you're using jquery but there's equivalents for mootools or prototype.
Binding:
javascript: URLs are a horror to be avoided at all times;
inline event handler attributes aren't brilliant either, but OK for a bit of rapid development/testing;
binding from script, leaving the markup clean, is typically considered a best practice. jQuery encourages this, but there is no reason you can't do it in any library or plain JS.
Responses:
In jQuery return false means both preventDefault and stopPropagation, so the meaning is different if you care about parent elements receiving the event notification;
jQuery is hiding it here but preventDefault/stopPropagation have to be spelled differently in IE usually (returnValue/cancelBubble).
However:
You have a link that isn't a link. It doesn't link anywhere; it's an action. <a> isn't really the ideal markup for this. It'll go wrong if someone tries to middle-click it, or add it to bookmarks, or any of the other affordances a link has.
For cases where it really does point to something, like when it opens/closes another element on the page, set the link to point to #thatelementsid and use unobtrusive scripting to grab the element ID from the link name. You can also sniff the location.hash on document load to open that element, so the link becomes useful in other contexts.
Otherwise, for something that is purely an action, it would be best to mark it up like one: <input type="button"> or <button type="button">. You can style it with CSS to look like a link instead of a button if want.
However there are some aspects of the button styling you can't quite get rid of in IE and Firefox. It's usually not significant, but if you really need absolute visual control a compromise is to use a <span> instead. You can add a tabindex property to make it keyboard-accessible in most browsers although this isn't really properly standardised. You can also detect keypresses like Space or Enter on it to activate. This is kind of unsatisfactory, but still quite popular (SO, for one, does it like this).
Another possibility is <input type="image">. This has the accessibility advantages of the button with full visual control, but only for pure image buttons.
The only advantage that I can think of to using javascript:void(0) is that it will be supported even by the oldest browsers. That said, I would use one of the other unobtrusive approaches you have mentioned:
For most uses, event.preventDefault() and return false can be used interchangeably.
event.preventDefault() will prevent the page from reloading, as desired, but will allow the click event to bubble up to the parent. If you want to stop the bubbling, you can use it in conjunction with event.stopPropagation.
return false will additionally stop the event from bubbling up to the parent.
I say 'interchangeably' in the first point above because much of the time we do not care whether or not an event bubbles up to the parent(s). However, when do we need some fine-tuning, we should consider points two and three.
Consider the following example:
<div>Here is some text Click!</div>​
$("a").click(function(e) {
e.preventDefault();
});
$("div").click(function() {
$(this).css("border", "1px solid red");
});
​
Clicking on the anchor will prevent the default action of the event from being triggered, so the browser will not redirect to www.google.com. However, the event will still 'bubble up' and cause the div's click event to fire, which will add a border around it. Add e.stopPropagation() or just return false and the div's click event will not fire. You can mess with it here: http://jsfiddle.net/cMKsN/1/
Dreamweaver uses a nice little trick by default that I've started using.
<a href='javascript:;'></a>
It's small, it doesn't trip and anchors and it's library agnostic.
I tend to prefer using return false, as that gives the option to give the user a choice whether to continue that action, such as shown here, in quirksmode:
http://www.quirksmode.org/js/events_early.html#default
It's simple, it's old, but it works well, cross-browser, regardless of the version of javascript.
event.preventDefault() and return false; are one thing - they instruct the browser not to process the default action for the event (in this case, navigating to the href of the anchor tag that was clicked). href=javascript: and its ilk are something else - they're causing the default action to be 'do nothing'.
It's a question of style. Do you want to do all your work in the onclick, or do you want to be able to put actions in both the onclick and the href and rely on the capabilities of the browser to modulate between the two?
I like using href="javascript:void(0)" in the link as # implies jumping to the top of the page and that may in fact happen if for some reason your jQuery event does not load e.g. jQuery fails to load.
I also use event.preventDefault(); as it will not follow the link even if an error is encountered before return false; for example:
HTML:
<a id="link" href="http://www.google.com">Test</a>
jQuery Example 1:
$("#link").click(
function(){
alert("Hi");
invalidCode();
return false;
}
);
jQuery Example 2:
$("#link").click(
function(event){
event.preventDefault();
alert("Hi");
invalidCode();
return false;
}
);
Since invalidCode(); will throw an error return false is never reached and if jQuery Example 1 is used the user will be redirected to Google whereas in jQuery Example 2 he will not.
I think that I have seen as well javascript:; around as the web develops, is hard to keep track to the tricks that are available out there.. but this is mainly about accessability (besides javascript:void(0); ) and just a small correction is not javascript:void(0) but javascript:void(0); which means do nothing so pretty much as return false; although not sure if javascript:return false; does the same..
I always use and would suggest to use javascript:void(0); for a couple of reasons.. in my humble opinion, of course.
1.) I use it because of the same someone mentioned above.. href="#" is not appropriate as it might indicate going to the top and even in that case '#top' would be more adequate for that case. But also this can trigger something else in your code that makes use of # (hashes) so another reason is to avoid conflicts with other javascript that might be using #. And I tend to look for this when using a plugin for example, and replace them immediately.. href='#' to href='javascript:void(0);' or href='javascript:;'
2.) If I want to re-use a function for a group of specific Anchor tags, I can call it with the selector on any attribute without worrying about detecting the click event and preventing the default action and I do it without even thinking of it as a development preference.
3.) In most cases if you are doing link building using javascript:void(0); tries to make a link to not be followed as the old href= rel=nofollow so it avoid indexing links that are actions. I'm not so sure about this one merely because I heard that crawlers and robots can now read even Flash so would not be surprised if they can read javascript links
4.) Referring from 2.) you can target on a class like and forget about preventing the click event default action by using a href="javascript:void(0);" and then targetting the class directly from the selector at the jQuery function.
jQuery(function($)
{
//from the rel
$('a[rel="-your-rel-id"]') ... off('click').on('click',function()
//from the class
$('a.-the-class') ... off('click').on('click',function()
//from the id
$('a#-the-id').off('click').on('click',function()
{
--do something with this link
});
});
I rather feel more comfortable using the class as you can always do...
$(a#-your-id).hasClass(-yourclass-)
or any other interesting combination and affect many links.. so I really won't suggest to use the A as a selector solely..
Normally what I see in here being suggested is this:
jQuery(function($)
{
//from the rel
$('a[rel="-your-rel-id"]').on('click',function(event)
//do something
//prevent the click as is passed to the function as an event
event.preventDefault();
});
});
I'd rather not put JavaScript into the href because that's not what it's meant for. I prefer something like
Link

Categories