Cookies do not work

0

Hello folks a friend here in the forum helped me make a button and I thank him so much, it worked perfectly. But I failed to put cookies and I'm not understanding where I'm 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>
    
asked by anonymous 07.07.2016 / 22:26

1 answer

2

Good afternoon,

As you did not inform me what error I was giving, I put your code in a fiddle and there were some errors that related to the order of loading of the script.

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

So I put a addEventListener to the button, and I did some testing and the behavior (which I think is) looks like expected (at least it's reading and writing cookies correctly).

Fiddle: link

    
07.07.2016 / 23:48