-1

I have a few .html pages with some href links in each.
Please help me with a code to call a JS function on 3rd click from same IP on any of the links.

Example:
IP 111.111.111.111 clicks a link for the 1st time do nothing
IP 111.111.111.111 clicks a link for the 2nd time do nothing
IP 111.111.111.111 clicks a link for the 3rd time onclick="call_function();"

To get the IP I'll use the code from this answer https://stackoverflow.com/a/2031935/4805488

Any help is much appreciated ...

Community
  • 1
  • 1
Brooks
  • 119
  • 1
  • 8
  • On each click of a link send an ajax request to the server to get the number of clicked links till now. If the third link is clicked execute the link (don't prevent the default behavior) otherwise stop the default action. – Andreas Oct 12 '15 at 17:14

3 Answers3

1

Some ideas so you can achieve this:

This link can help you decide which solution is best between cookies and local storage.

Community
  • 1
  • 1
Mick F
  • 7,312
  • 6
  • 51
  • 98
1

Something like below...

Also, if you need this to last over time and switching pages etc., you need to both add an uniqe id to each link and then store it in a cookie or server side, based on how important it is with exactly 3 clicks per link.

Having the "data-clicked" added to a link, you can have other links which will not act in the same way.

window.addEventListener('click', function(e) {
  
    if (e.target.getAttribute("data-clicked") == undefined) { return true; };
    
    var clk = parseInt(e.target.getAttribute("data-clicked"));
  
    if (clk >= 2) {
      e.target.setAttribute('data-clicked', 0);
      
      alert("Clicked 3 times");
      
    } else {
      e.target.setAttribute('data-clicked', clk + 1);
      
    }
  
    e.preventDefault();
  
    return false;
  
});
<a href='http://stackoverflow.com/' data-clicked='0'> Click me 3 times </a>
Asons
  • 84,923
  • 12
  • 110
  • 165
1
<a onclick="call_function(this, alertMe);">click me</a>

You can do something like:

function call_function(element, callback) {
   //check to see if clicked before or else start with 0;
   var clicked = parseInt(element.getAttribute('data-clicked') || 0);
   // increment the amount of clicks
   clicked++;
   // store the click amount in a data attribute
   element.setAttribute('data-clicked', clicked);
   // return the callback when the click amount 3 or greater. 
   return clicked >= 3 ? callback() : false;
}

function alertMe() {
   alert('wow! 3 times is....')
}

alternatively you can use localStorage.setItem() and localStore.getItem() instead of setAttribute and getAttribute if you want the clicked number to persist over time (until localStorage is cleared again)

Tim van Oostrom
  • 1,961
  • 1
  • 12
  • 8
  • Try avoid adding handlers inline. It will make maintenance so much easier and html code so much cleaner. – Asons Oct 12 '15 at 17:42