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
Related
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.
Quick Question.
Should we put Javascript in the HREF or use onClick (event)?
Are there any pros/cons to using either one. Personally I think it's easier/cleaner to simply put code in the href, and not have to return false or worry about jumping to #
Are there any known browser specific issues with each method...
Examples:
Click Me
Click Me
Click Me
1) Rather use onclick. Be sure to have a rational fallback URL in href when JS is not allowed.
2) Rather than onclick="...", you should use event handler.
Find elements using jQuery or XPath, and then for each, call element.addEventListener().
element.addEventListener("click", function() { alert("bar"); }, false);
Or the old way...
element.onclick = function() { alert("foo"); };
Keeping the code separate from the html is cleaner IMO.
<a id="foo" href="#">Click Me</a>
Then in head or separate js file:
document.getElementByID("foo").onclick = function() { alert("hi"); }
I would personally not put the JavaScript code in the HTML. You should use an event listener that will get triggered when the <a> is clicked on.
Click Me
And then:
document.getElementById('linkA').addEventListener('click', function(e){
e.preventDefault(); // Prevents page from scrolling to the top
alert('foo!');
});
In the onclick event (although assigned with JS rather then the attribute) with a sensible href attribute. Build on things that work
Generally, I would externalize JavaScript but use thehref to call it:
Click Me
Although I think your quick alert example is fine as an exception to the rule.
However, if your using a JS library like jQuery you can of course assign events directly - see the first example in jQuery tutorial which looks at the anchor element http://docs.jquery.com/Tutorials:How_jQuery_Works
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();
});
});
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
How do I send a click event (JS or JQuery) to a parent object that is an anchor? My basic HTML looks like:
<a href="javascript:myFunc(1,2,3)">
<img id="btn1" src="myimg.png">
</a>
So I can easily reference the anchor through button via:
document.getElementById('btn1').parentNode
However,
document.getElementById('btn1').parentNode.click
while it doesn't seem to raise an error in the console on firebug, the javascript function doesn't seem to be firing either. How do I send a click to this thing. By the way, I don't have control of the HTML so I can't just ad an ID to the anchor tag.
Gone are the days when it's okay to use the href="javascript:blah", especially if you're using a library like jQuery, Dojo, ExtJs or the rest. Event handlers should always be attached outside of the HTML.
$(function() {
$("#btn1").click(function() {
$(this).parent().click();
};
});
Here is a snippet that you can test on SO pages (copy+paste into Firebug)
$("#hlogo a").click(function() {
alert("a!");
return false;
});
$("#hlogo a img").click(function() {
alert("img!");
$(this).parent().click();
});
Normal Links with Normal HREF's
// assuming the link is always the immediate parent of #btn1
$("#btn1").parent().trigger("click");
Links with Javascript-Commands as HREF's
I note in your case though that your HREF value is a call to a javascript function, with parameters. For this, you may want to evaluate that HREF, rather than click the link:
// run the href-javascript from the parent anchor
eval($("#btn1").parent().attr("href"));
I've built a test-case and used firebug to try both methods. The first returns 1, showing the link was clicked, but the javascript is never executed. The second method actually executes the javascript found within the HREF value of the link itself. This should be an adequate solution to your specific need.
EDIT: ignore this answer as it's no good for links; see the comments below.
The click property of an a element is a function property, aka a method; all you are doing is referencing the property, not invoking it.
document.getElementById('btn1').parentNode.click();
(note the () to cause the method to be invoked) should do it, though if you are using jQuery already then Jonathan Sampson's answer will do what you need - there's no point in loading the library and then not using it :-)
Although Jonathan's answer can be shortened, as jQuery provides a click method:
$("#btn1").parent().click();
jQuery way maybe like this:
$(event.target).closest('a').trigger('click')
or in your words something like this
$('#bth1').closest('a').trigger('click')