Search code examples
javascriptcookiesjquery-cookie

It is necessary that the script worked 1 time. How?


There is a script that writes the count to 3 and then blocks the display of the banner. But the problem is that if you refresh the page again and then the counter starts over again. How to avoid it? Tell me please

$('#grandSale').each(function(i) {
  var self = this,
      cookieCounter = $.cookie('disable_banner');
  if (cookieCounter && cookieCounter < 3) {
      cookieCounter++;
      $(self).show();
      $('#topbar').remove();
      $.cookie('disable_banner', cookieCounter, { expires: 365, path: "/" });
  } else {
      $.cookie('disable_banner', 0, { expires: 365, path: "/" });
  }
});

Solution

  • Remove the "else", modify slightly the condition and it should be fine. It seems you reset the counter and start over after reaching 3.

    $('#grandSale').each(function(i) {
      var self = this,
          cookieCounter = $.cookie('disable_banner') || 0;
      if (cookieCounter < 3) {
          cookieCounter++;
          $(self).show();
          $('#topbar').remove();
          $.cookie('disable_banner', cookieCounter, { expires: 365, path: "/" });
      }
    });