How to execute onClick and href both in an anchor tag (<a>)

19,976

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.

Share:
19,976

Related videos on Youtube

user2129794
Author by

user2129794

Updated on June 26, 2022

Comments

  • user2129794
    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
      BENARD Patrick over 10 years
      Please, share your someFunction(), and reedit your question ( onclick is between tags, it should be attribute)
  • user2129794
    user2129794 over 10 years
    will window.location.href open the link in new window or new tab.. I want it to be open in new tab.
  • BENARD Patrick
    BENARD Patrick over 10 years
    I'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
    Esko over 10 years
    Doesn'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
    user2129794 over 10 years
    its opening in new window sumtyms and in new tab sumtyms
  • Quentin
    Quentin over 10 years
    It doesn't matter at all what myFunction returns. What matters is what onclick returns. It returns undefined (because it has no return statement) so it won't stop the link from being followed.