How to execute onClick and href both in an anchor tag (<a>)
Solution 1
I think the easiest way to do it is to make your function return true, so that after the function is complete, the anchor tag will behave like it normally does. This way you can also use the target-attribute if you want to use new window:
function myFunction() {
alert("hello");
return true;
}
<a href='http://www.google.com' onclick="myFunction();" target="google">Click me</a>
Solution 2
I used jQuery, and I hope it's still understandable:
<a href="www.google.com" onClick=someFunction()>Click me </a>
It's executing the JavaScript function, but it is not taking me to the href link.
So one way is to add the redirection after your function:
function someFunction()
{
... Your code ...
window.location.href($(this).attr('href')); // <----- HERE
}
UPDATE AFTER COMMENT:
function someFunction()
{
... Your code ...
window.open($(this).attr('href'), '_blank'); // <----- HERE
}
Solution 3
You could do this a few ways,
<div onclick = "function();"><a href = "link.com">link here</a> </div>
or you could just use onclick on the a
itself
<a href = "link.com" onclick = "function();"> link here</a>
You're putting the onclick inside of the tags which is just for text. Place it in the first to use it as an attribute of the tag.
As Esko posted, in the function return true if you want the href to execute as well.
Related videos on Youtube
user2129794
Updated on June 26, 2022Comments
-
user2129794 almost 2 years
I have a link as follows:
<a href="www.google.com" onClick="someFunction()">Click me</a>
On clicking the link, it's executing the JavaScript function, but it is not taking me to the href link.
How can I achieve the same?
-
BENARD Patrick over 10 yearsPlease, share your someFunction(), and reedit your question ( onclick is between tags, it should be attribute)
-
-
user2129794 over 10 yearswill window.location.href open the link in new window or new tab.. I want it to be open in new tab.
-
BENARD Patrick over 10 yearsI'm agree with you, it's better, but the asker didn't want to share his function, so it was not possible to determine if he used return false or not :/ +1 for you
-
Esko over 10 yearsDoesn't really matter what the function returns, you can always wrap it in a new function that returns true if needed :) Anyway, I still think this is the best way to do what he asked.
-
user2129794 over 10 yearsits opening in new window sumtyms and in new tab sumtyms
-
Quentin over 10 yearsIt doesn't matter at all what
myFunction
returns. What matters is whatonclick
returns. It returnsundefined
(because it has no return statement) so it won't stop the link from being followed.