Hide div 24hr cookie javascript? [closed]

房东的猫 提交于 2019-11-28 02:18:47

Although T.J. Crowder is right in his comment that stackoverflow is not here for writing your code... I wrote some code for you. Here's a solution using jQuery. In it you'd use a <div id="popupDiv">...</div> for the message and a link in it with id "close" to close the div.

$(document).ready(function() {

  // If the 'hide cookie is not set we show the message
  if (!readCookie('hide')) {
    $('#popupDiv').show();
  }

  // Add the event that closes the popup and sets the cookie that tells us to
  // not show it again until one day has passed.
  $('#close').click(function() {
    $('#popupDiv').hide();
    createCookie('hide', true, 1)
    return false;
  });

});

// ---
// And some generic cookie logic
// ---
function createCookie(name,value,days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
  }
  else var expires = "";
  document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  }
  return null;
}

function eraseCookie(name) {
  createCookie(name,"",-1);
}

Here's a js fiddle: http://jsfiddle.net/FcFW2/1/. Run once and then run again. The second time the popup does not show.

this should get you started: http://www.quirksmode.org/js/cookies.html

the following examples use the functions declared in the above link.

creating a cookie:

// when the div is clicked
createCookie('hideSuggestionBox', 'true', 1);

reading a cookie:

// when deciding whether to show or hide the div (probably on document ready)
if (readCookie('hideSuggestionBox') === 'true') {
    // do not show the box, the cookie is there
} else {
    // the cookie was not found or is expired, show the box
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!