Go to another html file via JS - javascript

I have an
<a href= ./index2.html>
button in my index.html but now I want to change it so it also calls a function when it gets clicked, so I tried
<a href="./index2.html;javascript:randomFunction();"
but it doesn't work, how can I make an element make switch html page and call a function at once? Thanks!!

Assuming that you want to run the JS on the current page:
The quick and dirty method that you shouldn't use is to add an onclick attribute.
<a href="index2.html" onclick="randomFunction()">
The clean approach is to bind an event handler with JS.
reference_to_anchor.addEventListener('click', randomFunction);
(See the documentation linked above for details, and for work arounds to lack of support in older versions of IE).
(See also Progressive Enhancement and Unobtrusive JavaScript).
This will run the JavaScript on the page on which the link appears before the link is followed.
If, on the other hand, you want the JavaScript to run on the destination page:
You have a rather more complicated problem to deal with.
A new page means a new execution environment. Client side code on one page can't trigger client side code on the next.
I'd approach that problem by having a server side script generate index2 and include <script>randomFunction();</script> if a particular query string was present on the URI.

make it call the desired function via onclick event, at the end of the function do a:
window.location=url;
or if you want to change page and then call a function on the new one use a normal a tag to go to the new page, then:
window.onload=function(){
//do something
}

You can use onclick="javascript:randomFunction()"
For instance:
<a href="./index2.html" onclick="randomFunction()">

use onclick event to call a function

you can use onclick event of javascript.
function randomFunction(){
// do needfull code here.
}

Related

document.getElementById('myElement').click(); not working as desired

A very short summary of "why" I need this. I am using PlUpload which lets you upload files using Ajax while providing you back events like percentage, completion, etc. You instantiate the object, then call the "init" (telling it on which ID to "link to") and then add all the event listeners. Since the page which needs the object is created at run time and cannot include JS, I simply created a DIV (which I will make invisible when everything works...) in the main page with the links inside.
This is the link:
<a id="browse" href="javascript:;">Browse</a>
If I click it directly, it works.
When I create the new subpage in real-time, I want the link to be called when the user clicks on an image, like this:
<img onclick="document.getElementById('browse').click(); return false;" src="whatever.jpg">
But it doesn't seem to be working. If I use any other "clickable link" rather than the "browse", it works, so there is no apparent error in the syntax.
Please note that if I modify the link like this:
<a id="browse" onclick="alert('Hello'); return false;" href="javascript:;">Browse</a>
Then I can see the "Hello" popup when I click on the image.
I am a beginner in JS/HTML, so if this is an obvious problem... Sorry ;)
Or if you know of a better solution to the general problem (without jQuery please), I would be grateful :)
This is the init part of the PlUpload:
var uploader = new plupload.Uploader({
browse_button: 'browse',
url: 'newupload.php',
});
uploader.init();
Embed the element inside element and you can click on the image which will do the same effect.
<img src="..."></img>
Instead of using the click() method try using this:
$('#browse').trigger("click");
this should trigger the event of the link instead of listening to the event and if you dont want to use jQuery you can simply do this:
document.getElementById('browse').onclick();
Happy coding!

Onclick reload with other onclick function

Is there someone who know if its posible to use 2 onclick in 1 button?
I hope to get reload page when i push the button.
Here is the orginal button:
<a href="javascript:;" onclick="javascript:articleToCart('<z:esc mode="js" value=$z:value[article.number]>', document.getElementById('amount$z:iteration[article.current]').value)">
Best Regards
Frank
EDIT:
My version works, but i cant find the way to get the return false to work. This works in IE and Firefox.
<center><input type="button" class="flowbutton" value="Kjøp" onclick="document.location.reload(true);javascript:articleToCart('<z:esc mode="js" value=$z:value[article.number]>',document.getElementById('amount$z:iteration[art‌​icle.current]').value)"> </center>
If you call a function, which you already do, you can do as much in the javascript as you want.
<script type="text/javascript">
function articleToCartMain() {
articleToCart('<z:esc mode="js" value=$z:value[article.number]>', document.getElementById('amount$z:iteration[article.current]').value);
//Put other function calls in here as well
return false; //Prevents the page from reloading or scrolling to top
}
</script>
Do something
If you want this type of inline JS event handlers (in the HTML source file), just use a comma between the two statements you want to put on the click event.
If you add a handler with JS, don't do onclick = function() { //code of your second function }; because it'll overwrite previous handlers. in this case, addEventListener/attachEvent is the "clean" way to go.
Btw, about pseudoURLs (javascript:) :
in href properties of your links it's usually considered bad practice. If this is a button, for god's sake, use a <button>... all A tags should have a real URL in href property.
in the onclick ??? useless, erase it without fear.

page fetched by AJAX cannot execute any javascript

I have been with that a whole day..
I have a home page(index.php) and i have a small menu in it(made up of buttons) and a <div id=tab_contents></div>
i have used AJAX in such a way that whenever i click on any of these buttons, another page is loaded in the tab_contents-div.ie:home_tab0.php, home_tab1.php, home_tab2.php for each button respectively.
The page that i want to fetch with ajax should contain a <body onload=initialize()> ...</body> function.or it can contain a javascript code snippet to trigger the initilization() function.
that is when the button is clicked,the page lets say home_tab0.php is loaded, codes inside the home_tab0.php should trigger the initialization() frunction.
i have tried every possible way in my knowledge to make it work but without success...:(
please if i can get any help for this i would be so grateful.
With jQuery it's easy to call any function after the ajax call has returned, and data is loaded. I guess that's what you want to do. There are a few examples here:
http://api.jquery.com/jQuery.get/
E.g:
$.get('home_tab0.php', function(data) {
$('#tab_contents').html(data);
initialize();
});
This is a common problem. I recommend using jQuery and letting it take care of this for you. Reimplementing what they've done would be a waste of your time.
http://api.jquery.com/load/
$("#tab_contents").load("http://www.foo.com/loadContent");

href="javascript:" vs. href="javascript:void(0)"

Our web app is rendered totally on the browser.The server only talks to the browser through JSON messaging.
As a result, we only need a single page for the app and mostly all the <a> tags do not have a real href pointing to other pages.
In my quest of removing unnecessary things I was wondering if I can get rid of the zillions of void(0) we have in our code, as they seem useless:
<a onclick="fn()">Does not appear as a link, because there's no href</a>
fn is called
fn is called too!
Does anybody knows if using href="javascript:" can cause a problem?
It works even on IE7...
Please don't spend your valuable time to tell me inline javascript is bad, as this is generated by a template engine :)
It does not cause problems but it's a trick to do the same as PreventDefault
when you're way down in the page and an anchor as:
click here
you will jump to the top and the URL will have the anchor # as well, to avoid this we simply return false; or use javascript:void(0);
regarding your examples
<a onclick="fn()">Does not appear as a link, because there's no href</a>
just do a {text-decoration:underline;} and you will have "link a-like"
fn is called
fn is called too!
it's ok, but in your function at the end, just return false; to prevent the default behavior, you don't need to do anything more.
When using javascript: in navigation the return value of the executed script, if there is one, becomes the content of a new document which is displayed in the browser. The void operator in JavaScript causes the return value of the expression following it to return undefined, which prevents this action from happening. You can try it yourself, copy the following into the address bar and press return:
javascript:"hello"
The result is a new page with only the word "hello". Now change it to:
javascript:void "hello"
...nothing happens.
When you write javascript: on its own there's no script being executed, so the result of that script execution is also undefined, so the browser does nothing. This makes the following more or less equivalent:
javascript:undefined;
javascript:void 0;
javascript:
With the exception that undefined can be overridden by declaring a variable with the same name. Use of void 0 is generally pointless, and it's basically been whittled down from void functionThatReturnsSomething().
As others have mentioned, it's better still to use return false; in the click handler than use the javascript: protocol.
Using 'javascript:void 0' will do cause problem in IE
when you click the link, it will trigger onbeforeunload event of window !
<!doctype html>
<html>
<head>
</head>
<body>
<a href="javascript:void(0);" >Click me!</a>
<script>
window.onbeforeunload = function() {
alert( 'oops!' );
};
</script>
</body>
</html>
This method seems ok in all browsers, if you set the onclick with a jQuery event:
Click me!
As said before, href="#" with change the url hash and can trigger data re/load if you use a History (or ba-bbq) JS plugin.
you could make them all #'s.
You would then need to add return false; to the end of any function that is called onclick of the anchor to not have the page jump up to the top.
I usually do not use any href and change the aspect with css, making them seems link. Thus you do not have to worry about link effect at all, except for the event handler of your application
a {
text-recoration: underline;
cursor: pointer;
}
javascript:void(0); --> this executes void function and returns undefined. This could have issues with IE.
javascript:; --> this does nothing. safest to create dead links.
'#' --> this means pointing to same DOM, it will reload the page on click.
Why have all the click events as a href links?
If instead you use span tags with :hover CSS and the appropriate onclick events, this will get around the issue completely.

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