Javascript Click Counter

I have this javascript:


<script type="text/javascript">
var clicks = 0;
function linkClick(){
    document.getElementById('clicked').value = ++clicks;
}

document.write('<a href="#" onclick="linkClick()">Click Me!</a>');
</script>

The above counts clicks.


You have clicked the link <input id="clicked" size="3" onfocus="this.blur();" value="0" > times.

The above displays the click count.

Can anyone show me how to make the page redirect to a specified URL after the 10th click?

In the linkClick function you would use the if statement to check if clicks is 10, though I would play it safe and check if it’s greater than or equal to 10.
If it is, yo can then use window.location.href to specify the new URL.

well I am having some success…


<script type="text/javascript">
var clicks = 0;
function linkClick(){
  document.getElementById('clicked').value = ++clicks;    
    if (clicks>3) {
  window.location.href = "http://www.google.com/";
    }
}
document.write('<a href="http://www.yahoo.com" onclick="linkClick()" target="_blank"><img src="img/site.png" alt=""></a>');
</script>

That works, but it only works with target=“_blank”. If I take the target blank off, it has a bit of a coronary. I think I have to find a way to add more javascript to make the link location a function. However, I am not a programmer – I’m just using the force here… I have done fairly well so far though, I think!

I think I need to change the document.write to another if then…

I think I need to say something like…

if clicks > 3 redirect, else display document.write…

I will go and play around. It will probably take me all day…


<script type="text/javascript">
var clicks = 0;
function linkClick(){
  document.getElementById('clicked').value = ++clicks;    
    if (clicks>3) {
  window.location.href = "http://www.google.com/";
    }
}
if (clicks>3) {
  window.location.href = "http://www.google.com/";
}
else {
  document.write('<a href="http://www.yahoo.com" onclick="linkClick()"><img src="img/site.png" alt=""></a>');
}
</script>

I think I need to do soemthing like that…