Run function only once after site loading

Asked

Viewed 2,609 times

6

A friend passed me a script of a box that opens when someone enters the site, however, when updating the page it appears again. You could help me?

Below the code:

function timer() {
    jQuery('.cloudbanner').hover(function () {
        jQuery('#follow').css('display', 'block');
        cronometro();
    });
    jQuery('.closeads').hover(function () {
        jQuery('#follow').css('display', 'block');
        cronometro();
    });
}

function cronometro() {
    setTimeout('amostra()', 3000);
}

function amostra() {
    jQuery('.cloudbanner').css('display', 'none');
    jQuery('#follow').css('display', 'none');
    jQuery('#fr').removeAttr('src');
}

function excludeDiv() {
    jQuery('#close').css('display', 'none');
    jQuery('.closeads').css('display', 'block');
    timer();
}

var numero = 5;
function chamar() {
    if (numero > 0) {
        document.getElementById('timers').innerHTML = --numero;
    }
}

setInterval("chamar();", 900);
setTimeout("excludeDiv();", 10000);

I imagine it has to do with cookie and I should create one, but I don’t know how to.

  • Do you want him to run once and never refresh the page? That’s it?

  • Is using PHP?

  • I’m using it in Wordpress, in the header (index.php). What I wanted is for it to appear only once a day.

  • I suggest the quick and easy sessionStorage. Saves variables while running the Browser. When you close the Browser variables are cleared.

2 answers

3

Using javascript only:

function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime( d.getTime() + (exdays * 24 * 60 * 60 * 1000) );

    var expires = 'expires=' + d.toUTCString();
    document.cookie = cname + '=' + cvalue + '; ' + expires;
}

function getCookie(cname) {
    var name = cname + '=';
    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);
        if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
    }

    return '';
}

In your scenario, the use would be basically like this:

// Pega o valor do cookie "flag", se existir
var flag_alert = getCookie("flag");

// Se o cookie não existe -> o usuário nunca viu o alerta
if ( flag_alert != '' ) {
    document.getElementById('alert-id').style.display = 'block';

    // Seta um cookie com duração de 30 dias
    setCookie("flag", true, 30);
} else {
    document.getElementById('alert-id').style.display = 'none';
}

Using a plugin called jQuery Cookie:

// Cria um cookie com duração de 30 dias
$.cookie(
    "alert_flag",
    true,
    {
        expires: 30 
    }
);

// Pegar valor do cookie
$.cookie("alert_flag");

// Deletar um cookie
$.cookie("alert_flag", null);

Mozilla also created a simple framework for writing/reading cookies in javascript.

But if you want to maintain the assertiveness of this warning to be shown only once to the user it is better to save this flag in the bank, then at the time of login you save it in the session and do the checks, if you want this approach let me know that I mount a code for you.

1

I made a code that you can put at the top of the page.

<?php
  session_start();
  if(!isset($_SESSION["caixinha"])){
    //pega a hora que a página foi carregada
    $_SESSION["hora"] = date('H');

    //se não existir é porque a caixinha não foi mostrada.
    echo"<script>funçãoQueMostraCaixa();</script>";
    $_SESSION["caixinha"] == 1;
  }else if($_SESSION["hora"] != date('H')){
    //se passar uma hora ele chama a função para mostrar a caixinha de novo
    echo"<script>funçãoQueMostraCaixa();</script>";
    //atualiza a hora
    $_SESSION["hora"] = date('H');
  }
?>

It creates a Session, and picks the time when the page is updated. In other Palavas it will show the box that you only once an hour. (But you can change it to a day by changing the date variable('H')

  • Analyzing my code, I should put what in place of the "box" and the "function"?

  • "Box" is just the name of Septssion, you can leave it the way it is. / "functionQueMostraCath" would be the name of the function you set, it is the function that makes your box appear.

Browser other questions tagged

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