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
I'm new to JavaScript and want a function that activates when you click on a link that leads outside the website. It should alert that you are about to leave the page and bring up a box that says "Do you really want to leave the site?" with response alternatives "OK" and "Cancel".
I've managed to do this like this (with an img that works like a link):
HTML:
<a href="http://www.urbanoutfitters.com"
onClick="return confirm('Do you really want to leave the site?')"
class="relaterade"> <img src="img5.jpg"/> </a>
I wonder if you can make a function so all in the class "relaterade" gets this confirm box instead of writing this on every single link. Maybe with document.getElementByCLassName? I want all JavaScript in a separate document.
Thanks! :)
You can get the element collection by doing document.getElementsByClassName. You must then loop through the collection and set the onclick event handler
var elements = document.getElementsByClassName('yourclass');
for (var element in elements) {
elements[element].onclick = function() {
return confirm('are you sure?');
}
}
this is from the top of my head, so dont know if it works for sure.
You could do this more easily with a library like jQuery though, cause IE < 9.0 will fail on the getElementsByClassName function
I have a button that triggers a modal window to show up. Because of data-toggle="modal" the url is not changed to www.doman.com/index.html#modalDiv, and I need it to change.
Is there an elegant way to achieve this?
Only thing that comes to my mind is to have a script that will add the hash to the url, but I was wondering if there is simpler solution.
It looks like you will have to override the default handling of data-modal, since its code in Bootstrap includes a return false.
You will have to create your own workaround. Something like:
Remove data-toggle="modal" and add a class of launch-modal to the <a> element
Then some javascript:
$('a.launch-modal').click(function (e) {
var modalId = $(this).attr('href');
$(modalId).show();
});
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.
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.