Reputation: 2433
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!!
Upvotes: 0
Views: 3797
Reputation: 944546
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.
Upvotes: 3
Reputation: 6736
you can use onclick
event of javascript.
<a href="./index2.html" onclick="return randomFunction();"></a>
function randomFunction(){
// do needfull code here.
}
Upvotes: 0
Reputation: 724
use onclick event to call a function
<a href="index2.html" onclick="javascript:randomFunction();"></a>
Upvotes: 0
Reputation: 71009
You can use onclick="javascript:randomFunction()"
For instance:
<a href="./index2.html" onclick="randomFunction()">
Upvotes: 0
Reputation: 1888
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
}
Upvotes: 0