Search code examples
jqueryruby-on-railsmousedown

Elegant way with Jquery to track document clicks persisted


I'm trying to persist some data which is how many times a user does the mousedown on the entire document. The problem is dealing with redirects and freshing pages which with my means lose all persisted data. This is a bit of a hack I created.. There must be a more elegant way with javascript/jquery to persist data and check the value on redirects?

       $(document).click(function(m) {
if ($.cookie('_click_count') == null) {
  $.cookie('_click_count', 1, {path: '/'});
}
else {
  $.cookie('_click_count', 2, {path: '/'});
}

});

$(document).mousedown(function(e) {
 if ($.cookie('_click_count') == 2) {
     $("#freeModal").appendTo("body");
     $("#freeModal").modal('show');
   }
  }
});

Solution

  • Ok, I think you want increment you click counts.

    So, you can track it like this:

    $(document).on("click", function(){
    
        var click_count = parseInt($.cookie('_click_count')); // get clicks from cookie
    
        if (click_count < 10 && click_count != NaN) // if count was started
            $.cookie('_click_count', click_count + 1, {path: '/'}); //  increase clicked count
    
        else if (click_count === 10) // if you reached at 10
            // do action
    
        else // if you want to start again
            $.cookie('_click_count', 1, {path: '/'});
    
    })