Show Div only on the second pageview and delete the cookie at a given time

Asked

Viewed 179 times

2

I already searched and found nothing related, wanted a code to show a DIV in the second pageview of a person on a site, and not show more in a predetermined period.

1 answer

1

You can create a cookie with the current date and then search for that cookie. In the second view add another variable to the cookie to know that it has already been seen.

For example:

// gerar um timestamp em milisegundos
var agora = Date.now(); // ou "new Date().getTime();" em browsers antigos

// ler a data do cookie, se houver
var dataCookie = document.cookie.match(/_criado=([\d]+)/);
dataCookie = dataCookie ? parseInt(dataCookie[0], 10) : agora;

// procurar no cookie por "_criado"
if (document.cookie.indexOf('_criado' == -1)){
    // primeira visita: criar o cookie
    document.cookie = document.cookie + '; _criado=' + agora + ';';
}
else if (document.cookie.indexOf('_segundavisita' == -1) && dataCookie + 2629740000 - agora > 0){
    // segunda visita e caso o cookie esteja dentro de 1 mês de validade
    document.cookie = document.cookie + ' _segundavisita=true;';
    // corre aqui o código da segunda visita
}

Note: 2629740000 is 1 month in milliseconds

Browser other questions tagged

You are not signed in. Login or sign up in order to post.