Search code examples
htmlonclickhttp-redirecthref

HTML onclick for A href does not work


Can I run onClick first. This code does not seem to work unless onClick needs window.location inside it?

<a onclick="click.php?add=yes&goto=http://refererurl.com/" href="http://refererurl.com/">advert</a>

Here it works a bit like Google where the user and search engine thinks the link is http://refererurl.com/ - however, the user is take to the click.php file first and then redirect.


Solution

  • This adjustment should do the trick.

    <a onclick="window.location.href='click.php?add=yes&goto=http://refererurl.com/';return false;" href="http://refererurl.com/">advert</a>
    

    As Pekka said in his comment, the value of an onclick attribute should be executable javascript code. So, I changed the contents to two javascript statements.

    1. window.location.href = {url};
    2. return false;

    The first statement tells the browser to go to a specified url.

    The second statement prevents the browser from performing the default behavior for clicked links. If the second statement was not included, then the browser would have gone to the url specified in the href attribute.