OnClick opens new windows but also changes current window - javascript

I'm using IE8. I've setup the following link:
<a href="terms.html" onclick="window.open(this.href,'targetWindow','toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=400,height=600')" />Terms & Conditions</a>
When I click it. I get the pop up the way I want. But it also sets the current windows to the same URL. I know I'm missing something silly. Just can figure it out.
Thanks!

Add return false; after window.open like below :
<a href="terms.html" onclick="window.open(this.href, 'targetWindow', 'toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=400,height=600');return false;" />Terms & Conditions</a>

Since you're clicking a <a>-link, your browser will automatically follow it. You need to make the onclick method return false for it to not open that page in your current window. It's also good to extract all JavaScript code from HTML, so that's something you should look into. However, this solution seems to do the trick:
HTML
<a href="terms.html" onclick="return openWindow('terms.html')" />Terms & Conditions</a>
JavaScript
function openWindow(href) {
window.open(href,'targetWindow','toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=400,height=600');
return false;
}

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

window.open sends the current window to 0

On a page (we'll call it: domain.com/subdirectory/page.html) I have a link like this:
Link
The new window opens perfectly, but the problem is, the pre-existing window gets redirected to {domain.com}/{subdirectory}/0 and I can't figure out why it's adding the 0 to the subdirectory and trying to go there.
I have tried moving the window.open to the onclick and making the href "void(0)" and even changed it to a span with an onclick, but I get the same results no matter which option I try. All I want is for the new window to pop up and for nothing to happen to the page you're already on.
The same thing happens in IE9 and in Chrome.
The reason I am using the window.open and not target="_blank" is because I also want to remove the menu and other stuff from that window to save space.
Answer Discovered
When I summarized the problem, I simplified my code too much as to make it impossible for anyone to answer (not by intention of course). I apologize for this.
Here's the actual window.open command (minus the URL): window.open('[hidden url]'_blank',height='400px',width='450px',location=0,menubar=0,resizable=0,status=0,titlebar=0,toolbar=0);
The problem was the "location=0". When I read a tutorial on window.open, it said to set this to 0 if I didn't want the URL shown. Personally, I didn't care, but I figured, the more real estate for information display the better. As it turns out, "location" is a URL and not a boolean property.
Once I removed the "location=0" it began functioning as expected/desired.
Thank you for trying to help.
Use an onclick and return false from the event handler:
Link
I also recommend separating your Javascript from your HTML. If you just have the one link you could do something like:
<a id="linkid" href="someurl" target="_blank">Link</a>
Then somewhere before your closing </body> tag and after that link tag:
<script>
document.getElementById('linkid').onclick = function(){
window.open('someurl','_blank');
return false;
}
</script>
You need to put it in an onclick event. You need to also add in return false; to stop the browser from following the link.
Link
jsFiddle of it working.
Here's another, slightly cleaner way to do it:
<a id="link" href="#">Link</a>
<script type="text/javascript">
var link = document.getElementById("link");
link.onclick = function() {
window.open('someurl','_blank');
return false;
}
</script>
I don't know your scenario, but this is probably the ideal way to do it:
<a target="_blank" href="someurl">Link</a>
Clean and simple, and it does the exact same thing.
When I summarized the problem, I simplified my code too much as to make it impossible for anyone to answer (not by intention of course). I apologize for this.
Here's the actual window.open command (minus the URL): window.open('[hidden url]'_blank',height='400px',width='450px',location=0,menubar=0,resizable=0,status=0,titlebar=0,toolbar=0);
The problem was the location=0. When I read a tutorial on window.open, it said to set this to 0 if I didn't want the URL shown. Personally, I didn't care, but I figured, the more real estate for information display the better. As it turns out, location is a URL and not a boolean property.
Once I removed the location=0 it began functioning as expected/desired.
You should try to learn JavaScript. Its really powerful and the basic things aren't very hard to learn.
There is an JavaScript object named window with an attribute (variable) called location. That is the URL of your page so, with the window.open(..., location = 0, ...); you were setting the URL of the page you wanted to open as http://the_page_you_are_calling_from_url/0.
So... yes, you were correct that location was the problem.
If you wish, take a look at Mozilla window API

IE not triggering onclick

For some reason IE won't trigger an onclick event. I have a link in my webpage which should renew a captcha image, but no matter what I try, the onclick event won't trigger. I even tried this to test the onclick event:
<a href="#" id="rc" onclick='alert("test"); return false;'>change image</a>
But nothing happened. I also tried to add the onclick event using js in the window.onload event, same result. All other javascript scripts do work, so js is working. Does anyone has any idea why this doesn't work?
by the way, the event doesn't work in any version of IE, and it does work in any other browser.
Edit: If you want to see the full source, go to: http://www.rosegardenvoorburg.nl/Contact?stackoverflow
The page is in Dutch, but the sourcecode is (of course) HTML, so you must be able to understand that.
edit2: I've found a solution myself, and you're never gonna believe what's wrong:
When I'm logged in to the control panel, a div is added at the top of the page, similar to the one shown in ie7 (which tells you you're browser is too old). However, when I don't add a border to that div, the captcha refresh button doesn't work. This doesn't make any sense at all, but at least I've found a solution...
Try with the below:
<a href="javascript:void(0);" id="rc" onclick='alert("test"); return false;'>change image</a>
Also have a look at Which "href" value should I use for JavaScript links, "#" or "javascript:void(0)"?
You are doing it in the wrong order
FIRST add the onload, THEN change the source
var cImg;
function renewCaptcha(){
cImg = new Image();
cImg.onload=function(){document.getElementById("captcha").src = cImg.src;};
cImg.src='/Img/captcha/securimage_show.php?' + Math.random();
}
Few tips to ponder!
check if javascript:alert("test") on your ie address bar pops up the message.
Also check and make sure that javascript option is not turned off.
You may also want to reset your ie settings and see if it work.
Also try to see if same works on your fellow colleague's computer.

JavaScript - href vs onclick for callback function on Hyperlink

I want to run a simple JavaScript function on a click without any redirection.
Is there any difference or benefit between putting the JavaScript call in the href attribute (like this):
....
vs. putting it in the onclick attribute (binding it to the onclick event)?
bad:
<a id="myLink" href="javascript:MyFunction();">link text</a>
good:
<a id="myLink" href="#" onclick="MyFunction();">link text</a>
better:
<a id="myLink" href="#" onclick="MyFunction();return false;">link text</a>
even better 1:
<a id="myLink" title="Click to do something"
href="#" onclick="MyFunction();return false;">link text</a>
even better 2:
<a id="myLink" title="Click to do something"
href="PleaseEnableJavascript.html" onclick="MyFunction();return false;">link text</a>
Why better? because return false will prevent browser from following the link
best:
Use jQuery or other similar framework to attach onclick handler by element's ID.
$('#myLink').click(function(){ MyFunction(); return false; });
Putting the onclick within the href would offend those who believe strongly in separation of content from behavior/action. The argument is that your html content should remain focused solely on content, not on presentation or behavior.
The typical path these days is to use a javascript library (eg. jquery) and create an event handler using that library. It would look something like:
$('a').click( function(e) {e.preventDefault(); /*your_code_here;*/ return false; } );
In terms of javascript, one difference is that the this keyword in the onclick handler will refer to the DOM element whose onclick attribute it is (in this case the <a> element), whereas this in the href attribute will refer to the window object.
In terms of presentation, if an href attribute is absent from a link (i.e. <a onclick="[...]">) then, by default, browsers will display the text cursor (and not the often-desired pointer cursor) since it is treating the <a> as an anchor, and not a link.
In terms of behavior, when specifying an action by navigation via href, the browser will typically support opening that href in a separate window using either a shortcut or context menu. This is not possible when specifying an action only via onclick.
However, if you're asking what is the best way to get dynamic action from the click of a DOM object, then attaching an event using javascript separate from the content of the document is the best way to go. You could do this in a number of ways. A common way is to use a javascript library like jQuery to bind an event:
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<a id="link" href="http://example.com/action">link text</a>
<script type="text/javascript">
$('a#link').click(function(){ /* ... action ... */ })
</script>
EDITOR WARNING: See the comments, the use of 'nohref' is incorrect in this answer.
I use
Click <a nohref style="cursor:pointer;color:blue;text-decoration:underline"
onClick="alert('Hello World')">HERE</a>
A long way around but it gets the job done. use an A style to simplify
then it becomes:
<style> A {cursor:pointer;color:blue;text-decoration:underline; } </style>
<a nohref onClick="alert('Hello World')">HERE</a>
The top answer is a very bad practice, one should never ever link to an empty hash as it can create problems down the road.
Best is to bind an event handler to the element as numerous other people have stated, however, do stuff works perfectly in every modern browser, and I use it extensively when rendering templates to avoid having to rebind for each instance. In some cases, this approach offers better performance. YMMV
Another interesting tid-bit....
onclick & href have different behaviors when calling javascript directly.
onclick will pass this context correctly, whereas href won't, or in other words no context won't work, whereas <a onclick="javascript:doStuff(this)">no context</a> will.
Yes, I omitted the href. While that doesn't follow the spec, it will work in all browsers, although, ideally it should include a href="javascript:void(0);" for good measure
the best way to do this is with:
The problem is that this WILL add a hash (#) to the end of the page's URL in the browser, thus requiring the user to click the back button twice to go to the page before yours. Considering this, you need to add some code to stop event propagation. Most javascript toolkits will already have a function for this. For example, the dojo toolkit uses
dojo.stopEvent(event);
to do so.
In addition to all here, the href is shown on browser's status bar, and onclick not. I think it's not user friendly to show javascript code there.
This works
Click Here
Having javascript: in any attribute that isn't specifically for scripting is an outdated method of HTML. While technically it works, you're still assigning javascript properties to a non-script attribute, which isn't good practice. It can even fail on old browsers, or even some modern ones (a googled forum post seemd to indicate that Opera does not like 'javascript:' urls).
A better practice would be the second way, to put your javascript into the onclick attribute, which is ignored if no scripting functionality is available. Place a valid URL in the href field (commonly '#') for fallback for those who do not have javascript.
it worked for me using this line of code:
<a id="LinkTest" title="Any Title" href="#" onclick="Function(); return false; ">text</a>
First, having the url in href is best because it allows users to copy links, open in another tab, etc.
In some cases (e.g. sites with frequent HTML changes) it is not practical to bind links every time there is an update.
Typical Bind Method
Normal link:
<a href="https://www.google.com/">Google<a/>
And something like this for JS:
$("a").click(function (e) {
e.preventDefault();
var href = $(this).attr("href");
window.open(href);
return false;
});
The benefits of this method are clean separation of markup and behavior and doesn't have to repeat the function calls in every link.
No Bind Method
If you don't want to bind every time, however, you can use onclick and pass in the element and event, e.g.:
Google
And this for JS:
function Handler(self, e) {
e.preventDefault();
var href = $(self).attr("href");
window.open(href);
return false;
}
The benefit to this method is that you can load in new links (e.g. via AJAX) whenever you want without having to worry about binding every time.
Personally, I find putting javascript calls in the HREF tag annoying. I usually don't really pay attention to whether or not something is a javascript link or not, and often times want to open things in a new window. When I try doing this with one of these types of links, I get a blank page with nothing on it and javascript in my location bar. However, this is sidestepped a bit by using an onlick.
The most upvoted answer is obsolete today
I would recommend the exact opposite, see step by step with reasons:
good:
<a id="myLink" href="javascript:MyFunction();">link text</a>
It depends, might be good, because crawlers follows href targets and if there is any meaningful content produced by MyFunction() (dynamic link), it is followed more likely than in the click event, which may have multiple or none listeners.
bad:
<a id="myLink" href="#" onclick="MyFunction();">link text</a>
# means meaningless link, crawlers are often interested only in first x links, so it can prevent them to follow some meaningful links later in the page.
worse:
<a id="myLink" href="#" onclick="MyFunction();return false;">link text</a>
Same as previous plus return false prevents following the link. If some other scripts want to add another listener and update the target (say to redirect via proxy), they can't without modifying the onclick (okay, it's just a minor setback as such use cases are rather theoretical).
worst:
Use jQuery or other similar framework to attach onclick handler by element's ID.
$('#myLink').click(function(){ MyFunction(); return false; });
jQuery is outdated in 2020+ and should not be used in new projects.
Events in href
The href attribute handler doesn't get the event object, so the handler doesn't implicitly see which link was the source. You can add it in onclick handler, which fires before the href is followed:
<a href="javascript:my_function(event2)" onclick="event2=event">
JS based link
</a>
<script>
function my_function(e) {
console.log(e.target); // the source of the click
if(something) location.href = ...; // dynamic link
}
</script>
One more thing that I noticed when using "href" with javascript:
The script in "href" attribute won't be executed if the time difference between 2 clicks was quite short.
For example, try to run following example and double click (fast!) on each link.
The first link will be executed only once.
The second link will be executed twice.
<script>
function myFunc() {
var s = 0;
for (var i=0; i<100000; i++) {
s+=i;
}
console.log(s);
}
</script>
href
onclick
Reproduced in Chrome (double click) and IE11 (with triple click).
In Chrome if you click fast enough you can make 10 clicks and have only 1 function execution.
Firefox works ok.
<hr>
<h3 class="form-signin-heading"><i class="icon-edit"></i> Register</h3>
<button data-placement="top" id="signin_student" onclick="window.location='signup_student.php'" id="btn_student" name="login" class="btn btn-info" type="submit">Student</button>
<div class="pull-right">
<button data-placement="top" id="signin_teacher" onclick="window.location='guru/signup_teacher.php'" name="login" class="btn btn-info" type="submit">Teacher</button>
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
$('#signin_student').tooltip('show'); $('#signin_student').tooltip('hide');
});
</script>
<script type="text/javascript">
$(document).ready(function(){
$('#signin_teacher').tooltip('show'); $('#signin_teacher').tooltip('hide');
});
</script>
I experienced that the javascript: hrefs did not work when the page was embedded in Outlook's webpage feature where a mail folder is set to instead show an url
click here
I cant belive that +13 years later, all of these answers are semantically incorrect! An anchor element <a>:
...with its href attribute, creates a hyperlink to web pages, files, email addresses, locations in the same page, or anything else a URL can address.
Content within each should indicate the link's destination. If the href attribute is present, pressing the enter key while focused on the element will activate it.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a
Therefore, using an href= for javascript is bad practice and poor web semantics. You should rather be using an onclick= event handler attribute on a button element, as:
The HTML element is an interactive element activated by a user with a mouse, keyboard, finger, voice command, or other assistive technology. Once activated, it then performs a programmable action, such as submitting a form or opening a dialog.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button
and the event handler onclick=:
All event handler attributes accept a string. The string will be used to synthesize a JavaScript function like function name(/args/) {body}, where name is the attribute's name, and body is the attribute's value.
https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes#event_handler_attributes
As you are not navigating to a URL or a Link destination, but rather triggering a Javascript function the correct way to do this is to use onclick. And if you need the style of an anchor tag on a button, just use CSS.
The bottom line is: just because you can do it doesn't mean you should.
This works as well
<a (click)='myFunc()'>Click Here </a>
(onclick) did not work for me in an Angular project with bootstrap.

Categories

Resources