jQuery click not recognized - javascript

I have a test page here: http://www.problemio.com/test.php
and if you press "Click To Test Signup" you get a form. If on that form, you click "Log In" it recognizes that you clicked that, and opens the login form.
But the problem is that on the login form, if you press "create profile" it actually goes to the url of the href tag and not to the jQuery click event.
My quetion is what is the best practice of doing this? I hered of something called "prevent default behavior" but not sure how/when it should be used.
I am guessing that if the user has JS disabled, they should still be able to log in. How can I set it up so that users can log in and make accounts in the jQuery way first, and some default way if they have JS disabled?
Thanks!

You can do this with pure jQuery with
$("#createprofilelink").click(function(event) {
event.preventDefault();
{create profile logic}
});
more details of this can be seen in the jQuery documentation http://api.jquery.com/event.preventDefault/
Edit: I removed this because of #maxedison comment that it stops the jQuery event from firing but I have just tested this and the jQuery event fires but the link does not go to the address.
<a id="thelink" href="http://www.google.com" onclick="return false;">the link</a>
<script>
$('#thelink').click(function(){alert('alert me');});
</script>
As for the JS being disabled part of the question the link really should point to to a real form to fill in, as Taryn East correctly says, so the user gets the same functionality even if the user experience is lower by not using JavaScript.
You could even go down the noscript route
<noscript>
<div>Your user experience would be far improved if you
enable JavaScript but if you insist,
Click Here to create your profile</div>
</noscript>

To fix you link-gazumping problem, indeed, as #kamui says, use return false;
But as to your JS-disabled question - point the href at a real URL -> preferably the same URL as your JS-enabled stuff - or the same form, but in a new window.

I could not follow the link due to firewall restrictions on my side but...
You'll want to use whats called unobtrusive javascript.
http://en.wikipedia.org/wiki/Unobtrusive_JavaScript
This means if JS is available it will use it, if not continue working as plain html.
using jQuery you would first attach the click event to your button in the $.Ready() method.
<a id='btnTest' href='login.html' />
$(document).ready(function () {
// Attach click event to btnTest
$("#btnTest").click(function (e) {
// do logic
return false; // Returning false here will stop the link from following login.html.
});
});
Hope this helps.

Related

JSF commandButton action is invoked from javascript even if false is returned [duplicate]

Hey there is a link in my program as shown and onclick it calls the function clearform as shown:
Html Code:
<a class="button" href="Cancel" style="left: 55%;" onclick="clearForm()">Cancel</a>
JavaScript Code:
function clearForm(){
document.getElementById("subjectName").value = "";
return false;
}
return false is not working in this code. actually the first line of the function executed successfully but the return false was failed. I mean page is redirected to url "Cancel".
Change your code as
<a class="button" href="Cancel" onclick="return clearForm()">Cancel</a>
Your problem is you need to return the Boolean.
But, drop all that...
Attach your event unobtrusively...
element.onclick = clearForm;
Use preventDefault(). It is the modern way of acheiving that.
function clearForm(event) {
event.preventDefault();
}
<a class="button" href="Cancel" style="left: 55%;" onclick="clearForm();return false;">Cancel</a>
should work
Please note that if there is a bug or error in clearForm() then "return false" will NOT stop the anchor action and your browser will try to link to the href "Cancel". Here is the logic:
User clicks on anchor
onClick fires clearForm()
There is an error in clearForm() so Javascript crashes and stops all code execution.
return false is never fired because Javascript has already stopped.
If you are relying on a third party JavaScript API (I was using code supplied by Recyclebank to spawn a popup), and the third party API makes an update that breaks the JavaScript, then you'll have problems.
The following will stop the link under normal conditions and error conditions.
<a class="button" href="javascript:;" style="left: 55%;" onclick="clearForm();return false;">Cancel</a>
The return false; somehow needs to be right at the front.
(In ALL situations I've dealt with over the past months - may or may not be a bug).
Like this: onclick="return false; clearForm();"
Besides that, as mentioned by others as well, you need to return it from the onclick, not just from the function.
In your case: onclick="return clearForm()".
Keep in mind that some browser extensions may interfere with proper operation of links. For example, I ran into a situation where someone had both AdBlock Plus and Ghostery enabled. Clicking a simple 'a' tag with an 'onclick="return SomeFunction();"' attribute (the function returned false) caused the browser to treat the click as a page transition and went to a blank page and the loading indicator just kept spinning. Disabling those browser extensions cleared up the problem.
Including this as an answer because this was the first page I landed on from Google.

Using 'href="#"' needs 2 Back presses in some browsers

I have javascript that uses 'href="#"' to call a function when it's clicked. The problem is that when I run it on Chrome, I need 2 Back presses to return to the referrer page, but on Opera, I only need 1 Back press.
I read the details about using 'href="#"' here:
What is href="#" and why is it used?
here is my test code:
<p>
<script type="text/javascript">
function testOnClick(){
document.write("onClick() support was detected!<br>");
}
</script>
</p>
Clicking on the link should clear the screen and display progress text<br />
<a onclick="testOnClick();" href="#!">
Click here to test onClick
</a>
You might need to use event.preventDefault();
function testOnClick(event) {
event.preventDefault();
document.write("onClick() support was detected!<br>");
}
It prevents your navigator to navigate to the # link, thus, having to press back.
You can also get similar functionality by using a different element and making it look like a link. If you aren't navigating the user to a different section of the page or a new page, for example, you probably should be using the <a> tag.
Here's a fiddle for what I mean: http://jsfiddle.net/2ph2d2gd/
The use case for this would be to open a modal, or do some other action that doesn't necessarily navigate the user anywhere. I don't know your specific circumstances, so you may or may not want to use something like this.
Note: I used alert instead of document.write because jsfiddle doesn't allow the latter.
HTML:
Clicking on the link should clear the screen and display progress text<br />
<span class="link" onclick="testOnClick();">
Click here to test onClick
</span>
CSS:
.link{
text-decoration:underline;
color:blue;
cursor:pointer;
}
Javascript:
function testOnClick(){
alert("onClick() support was detected!");
}
I've had good results leaving the href blank in this scenario. It doesn't reload the page with "#" at the end of the URL and events still fire.
I'm not sure how well that works with JS onclick, but you could replace that with jQuery.
<script type="text/javascript">
$(function() {
$("#link").on("click", function() {
alert("click");
});
});
</script>
<a id="link" href="">
Click here to test onClick
</a>
If you use href="#", make sure onclick always contains return false; at the end, that any called function does not throw an error and if you attach a function dynamically to the onclick property make sure that as well as not throwing an error it returns false.
OR
Use href="javascript:void(0)"
More information about why can be found in this question

javascript style alert with link before user navigates away from page

I am looking at having a alert style box show up when a user tries to leave the page but I what I wanted to do is have a share link in the alert style box
I have read this ticket javascript before leaving the page and now am unsure if this is possible.
I realise this will run
$(window).bind('beforeunload', function(){
alert("hi");
});
Now I know you cannot add links to an alert window so am trying to get round this another way but cant think of how i would display a alert/popup before going to another page that has a link in
Can anyone suggest anything - is there a plugin that might do this?
Its better you not do even if u do a hack as if you find a bug and use it to do it one they they will fix it and you will be again at same point. This is a security risk suppose i want to close a tab and in code you opne new popups or do malicious things???? So browserts dont allow it. If user wants to go they are allowed u can use standard
window.onbeforeunload = function() { return 'You have unsaved changes!'; }
if you like So try this. istead of custom things.
DEMO
You cannot add links to an alert window. What you could do is use a jQuery Plugin like http://jqueryui.com/dialog/#default and call it within beforeunload function.
HTML
<div id="dialog" title="My Link">
My Link
</div>
jQuery
$(window).bind('beforeunload', function(){
$( "#dialog" ).dialog();
});
OR if don't want to use jQuery you could use a window.open
eg: http://www.quirksmode.org/js/popup.html

Warning when clicking external links and how to add it to a link class

I'm not sure how to do a pop-up that warns when you are clicking on external links, using javascript.
I figured that it would be handy to put a class on my external links as well, but I'm not quite sure it's done correct as it is now either. This is the HTML I'm using at the moment:
<div id="commercial-container">
<img src="picture1.jpg" />
<img src="pciture2.jpg" />
<img src="picture3.jpg" />
<img src="picture4" />
</div>
I'm very new to javascript and very unsure on how to solve my problems. The pretty much only thing I figured out so far is that I will have to use window.onbeforeload but I have no clue on how to figure out how to write the function I need.
I want to keep my javascript in a separated .js document instead of in the HTML as well.
Call the confirm() function from the onClick attribute. This function returns true if the user clicks OK, which will open the link, otherwise it will return false.
<img src="picture1.jpg"/>
Hope this helps.
You can do it by adding a click event handler to each link. This saves having to use a classname.
window.onunload will run even if the user is just trying to close your site, which you may not want.
staying in site
going external
<script>
var a = document.getElementsByTagName('a');
var b = a.length;
while(b--){
a[b].onclick = function(){
if(this.href.indexOf('yourwebsitedomain.com')<0){
//They have clicked an external domain
alert('going external');
}
else{
alert('staying in your site');
}
};
}
</script>
Since you're new to Javascript I advice you to use a javascript framework to do all the "heavy work" for you.
For example with JQuery you can easily bind an onClick event to all external links by doing:
$(".external").click(function(event) {
var confirmation = confirmation("Are you sure you want to leave ?");
if (!confirmation) {
// prevents the default event for the click
// which means that in this case it won't follow the link
event.preventDefault();
}
});
This way every time a user clicks on a link with the external class, a popup message box asking for a confirmation to leave will be prompt to the user and it will only follow the link if the user says "yes".
In case you want only to notify without taking any actions you can replace the confirmation by a simple alert call:
$(".external").click(function(event) {
alert("You are leaving the site");
});
If the user click an image,div,.. you need to look for the parent node. !There could be several elements wrapped with a-tag.
document.addEventListener('click',function(event){
var eT=(event.target||event.srcElement);
if((eT.tagName.toLowerCase()==='a' && eT.href.indexOf('<mydomain>')<0)
|| (eT.parentNode!==null && eT.parentNode.tagName.toLowerCase()==='a'
&& eT.parentNode.href.indexOf('<mydomay>')<0))
{
//do someting
}
else if(eT...){
...
}
},false);
Two side notes:
If you want to keep track a user by cookie or something similar, it's good practice to check external links, set a timeout and make a synchronic get request to renew.
It's better to add the event to the document or a div containing all events and decide on target.

jQuery dialog call redirecting page

I'm using the jQuery dialog plugin.
The dialog div is set up (but not opened) on page load:
$(document).ready(function(){
$('#foo').dialog({autoOpen:false});
});
Then a hyperlink is supposed to open the dialog:
Show dialogue box
But this opens the dialog then a fraction later redirects to a page with the URL javascript:$('#foo').dialog('open');!
I have tried returning false:
Show dialogue box
But then the link doesn't respond at all when I click on it.
I know this must be to do with one of JavaScript's infamous subtleties but I can't work it out.
Can anyone help?
Then a hyperlink is supposed to open the dialog:
Show dialogue box
But this opens the dialog then a fraction later redirects to a page with the URL javascript:$('#foo').dialog('open');!
That shouldn't be happening. The pseudo-protocol javascript: doesn't involve a page load, and certainly not one via HTTP. I don't recommend it (I'd use jQuery's click handler instead), but it should work.
I have tried returning false:
...
But then the link doesn't respond at all when I click on it.
That also shouldn't be happening.
Your code as quoted is fine (works here, for instance: http://jsbin.com/inixa5), so the problem must lie in some other part of the page.
Update: Okay, that's weird, IE6 and IE7 didn't like that; I think it's because dialog returns a value. You can get around that either by wrapping up your call to open the dialog in a function and doesn't explicitly return anything:
Click Me
<script>
$("#foo").dialog({autoOpen: false});
function showDialog(selector) {
$(selector).dialog('open');
}
</script>
Or (and this is mega-hacky) by making sure the last expression in the javascript: block is undefined:
Click Me
<script>
$("#foo").dialog({autoOpen: false});
</script>
Or by using onclick:
Click Me
<script>
$("#foo").dialog({autoOpen: false});
</script>
But in any case, strongly recommend hooking things up with a DOM2 style event handler:
<a href="#" name='openSesame'>Click Me</a>
<script>
// This _can_ be immediately after the anchor, but I'd put it in
// a separate, since .js file for the page that you load just before
// the closing body tag.
$("#foo").dialog({autoOpen: false});
$("a[name=openSesame]").click(function() {
$("#foo").dialog('open');
return false;
});
</script>
Live example (Obviously, you can use any selector that makes sense, you don't have to give the anchor a name [or id].)
One of the nice things about this is that you can then have the anchor take the user somewhere meaningful and/or useful if JavaScript is disabled (something called progressive enhancement).
Change the link to:
<a href="javascript:void(0)" onclick="$('#foo').dialog('open')">
Show dialogue box
</a>
Best avoid putting javascript in the href.
Even better would be giving it a class and than adding a click event to it through jquery.

Categories

Resources