Cookies do not work

Asked

Viewed 63 times

0

Hello folks a friend here from the forum helped me make a button and I thank him very much, it worked perfectly. However I failed to put cookies and I don’t understand where I’m going wrong (I was following a video on youtube to do it)

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Contador</title>
</head>
<body>

<script language="JavaScript">


function dispara( span ) {
conta( span, document.getElementsByClassName(span)[0]);
}

function conta( botao, contador ) {

document.getElementById(botao).disabled=true;

if(validaCookie()){

contador.innerHTML = contador.innerHTML -1;
criarCookie(contador.innerHTML);

}
else{
contador.innerHTML = 60;
criarCookie(60);
}

if(contador.innerHTML <= 0) {
document.getElementById(botao).disabled=false;
invalidarCookie();
return false;
}

setTimeout( function(){conta( botao, contador )}, 1000 );
}

</script>

<input type="button" value="botao1" onclick="dispara('s1')" id="s1" class="btn">
<span class="s1" id="sp1">60</span>

<script type="text/javascript">
if(validaCookie()){
document.getElementById("sp1").innerHTML = lendoCookie();
}

//Criando o Cookie
function criarCookie(valorCookie){

//Criar objeto Date
var data = new Date()
//Setando o tempo de vida do Cookie
data.setTime(data.getTime() + 600000);

//Criando a estrutura do Cookie
document.cookie = "cookieCount="+valorCookie+"; expires="+
data.toUTCString()+"; path=/";

}

//Validando a existência do Cookie
function validaCookie(){
if(document.cookie.indexOf("cookieCount") == (-1)){
return false;
}else{
return true;
}
}

//Lendo o conteúdo do Cookie
function lendoCookie(){

//document.cookie retorna chave=valor
var valor = document.cookie.split("=");
return valor[1];

}

//Invalidando o Cookie
function invalidarCookie() {
document.cookie = "cookieCount=0; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/";
alert("Cookie invalidado!");
}


</script>

</body>
</html>

1 answer

2


Good afternoon,

as you did not inform which error was giving, I put your code in a fiddle and appeared some errors that related to the loading order of the script.

As a general rule, the ideal is to put the script at the end of the body and not use javascript inline to bind events, mainly because of the separation of concepts (yet, if javascript is at the end, it does not find the function that has not been loaded yet).

So I put a addEventListener to the button, and I did some tests and the behavior (which I think it is) seems as expected (at least it is reading and writing the cookies correctly).

Fiddle: https://jsfiddle.net/mrlew/ce153vaL/

  • Vlw, it was more or less what I really wanted! Now I’ll just put onload here!

Browser other questions tagged

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