-1

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.

TheBlackBenzKid
  • 26,324
  • 41
  • 139
  • 209
  • 3
    What you have in `onclick` is not valid JavaScript. That's probably why it doesn't do anything – Pekka Dec 28 '11 at 16:38

1 Answers1

5

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.

jessegavin
  • 74,067
  • 28
  • 136
  • 164
  • 1
    This worked. I tried parent.location and window.location and location.href - in a few possible combinations - I actually wanted window.location as I enjoy this one. Can I do this same code within the DIV tag? and if Yes how? – TheBlackBenzKid Dec 28 '11 at 16:42
  • I am glad that `window.location` brings you joy. You can do the same thing with a div, just add an `onclick` attribute with a similar value. – jessegavin Dec 28 '11 at 16:44
  • The only issue I have with the code - in Firefox, if I click the middle mouse button on the link - it opens the HREF link and not the onClick link – TheBlackBenzKid Dec 28 '11 at 16:47
  • @TheBlackBenzKid (@ 1st comment) That can't be true in full since `location.href` is just a synonym for `window.location.href`. It's because `window` is the all surrounding JavaScript object whose attributes we are accessing. Also `window` is an attribute of `window` so you could also have been written `window.window.window.location.href`. – Matteo B. Dec 28 '11 at 16:48
  • @Matmarbon - Yes, it never worked. I said I tried a few combinations and they did not work - I meant to say that jessegavin solution has worked - accept the new tab window issue. – TheBlackBenzKid Dec 28 '11 at 16:54
  • 1
    @TheBlackBenzKid I meant the exact opposite: The one of your tried combinations (namely `location.href`) must have worked but let us not quarrel, forget about it. To your problem: maybe http://stackoverflow.com/questions/3272715/problem-with-onclick-and-middle-button-on-mouse or http://stackoverflow.com/questions/152262/middle-click-new-tabs-and-javascript-links has the right answer. – Matteo B. Dec 28 '11 at 17:03