I would like to prompt the user once they click more than 3 links on a certain section of a website. I would like to know the best way to approach this.
Can I do this with strictly client-side Javascript? Or would this require some server-side code?
I've seen this used on a couple of real-estate sites and would like to experiment.
A bit extended example based on the code found in CJ's answer. Consider you have three files and links to each other in them:
<!-- test1.htm -->
<a href="test2.htm">Test2</a>
<a href="test3.htm">Test3</a>
<!-- test2.htm -->
<a href="test1.htm">Test1</a>
<a href="test3.htm">Test3</a>
<!-- test3.htm -->
<a href="test1.htm">Test1</a>
<a href="test2.htm">Test2</a>
In each file, you have also included the same script responsible for counting clicks on these links. The script contents would be like this:
var links = document.getElementsByTagName('a');
for(var i = 0, ii = links.length; i < ii; i++) {
links[i].addEventListener('click',ClickCounter,false);
}
function ClickCounter(e) {
if(localStorage.clickCount) {
if(+localStorage.clickCount === 3) {
alert("Three links visited already!");
e.preventDefault();
} else {
localStorage.clickCount = +localStorage.clickCount + 1;
}
} else {
localStorage.clickCount = 1;
}
}
This would allow the user to visit three links. After that, the user would get an alert box about having visited three pages already, and the e.preventDefault()
would keep the user on the current page.
Of course, the user could get around this kind of limiting by simply removing the appropriate localStorage entry, so if your goal is to do some sort of blocking or limiting, it should rather be done server-side in order to prevent easy user tampering. If your goal is to do something "harmless" (as in, the functionality is something that the users would generally consider beneficial), though, doing the whole thing client-side would probably be just fine.