Question

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?

Was it helpful?

Solution

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>

OTHER TIPS

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
}

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.

When the click event is attached on an anchor tag, it is handled by browser in a 'special' way.

The .click is not supposed to work with 'a' tags, because the browser does not support "fake clicking" with JavaScript.

I mean, you can't "click" an element with JavaScript. With 'a' tags you can trigger its onClick event, but the link won't change colors (to the visited link color, the default is purple in most browsers).

So it wouldn't make sense to make the "click" event work with 'a' tags since the act of going to the href attribute is not a part of the onClick event, but hardcoded in the browser.

But you can do some customization to an onclick handler so as to refer href link.

Let's have an example for it:

$('a').click(function () {
    window.open($(this).attr('href'));
});

Here is the http://jsfiddle.net/4Qku8/ demonstrating the same using jQuery.

For further details, please refer to Stack Overflow question Can I call jQuery's click() to follow an link if I haven't bound an event handler to it with bind or click already?.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top