How to know if a person has clicked on a DIV or not

Asked

Viewed 267 times

0

I have an ad and I want to know if the person has already clicked on the ad in the last 2 days.

If it has already clicked, it does not appear but, if it has not clicked, it still appears.

Something like that:

<!DOCTYPE html>
<?php
  setcookie("USER","sim", time() + 172800); // 86400 = 1 dia, 172800 = 2 dia
?>
<html>
<body>

<?php if (!isset($_COOKIE["USER"])): ?>
  <div class="anuncio">
    ANUNCIO PARA QUEM NÃO CLICOU AINDA!
  </div>
<?php else: ?>
  <div class="">
    OPS, VC JA CLICOU NÃO APARECER ANUNCIO
  </div>
<?php endif; ?>

</body>
</html>

But, how to know if he has already clicked into this <div>, that is, if he has already clicked on the ad

  • You can use javascript to create a cookie, when it clicks on the ad, and then check if the cookie exists.

  • https://stackoverflow.com/questions/36493716/onclick-javascript-cookie

  • Help me ? No java script manjo.

2 answers

1


Use Java script with ajax, to load the page in PHP when clicking the div!

<script type="text/javascript">
 function gravaCookieclique() {
  $.ajax({
   method: "POST",
   url: "gravacookieclique.php",
   data: { gravaCookieclique: "sim"}
  });
 }
</script>

And in PHP put your function with $_POST

0

A solution without PHP and cookie, only with JS and Localstorage:

//Elemento do anuncio
const anuncio = document.querySelector('#anuncio');

//Se houver o anuncio salvo
if (localStorage.anuncio) {
  //Cria um objeto de data com o valor salvo
  let data = new Date(localStorage.anuncio);
  //Adiciona dois dias a data criada
  data.setDate(date.getDate() + 2);

  //Compara a data salva com a data atual
  if (data > new Date()) {
    //Se a data salva + 2 dias for maior que a data atual, esconde o anuncio
    anuncio.style.display = 'none'
  }
}

//Adiciona um ouvinte de evento no elemento do anuncio
anuncio.addEventListener('click', function() {
  //Salva em localStorage a data
  localStorage.anuncio = new Date();
});
  • It didn’t help me.. because my page has php as well.. I wonder if he clicked.. if he ever clicked or put to show another page..

  • Anyway you will need JS to know whether or not the user clicked on the ad. It is possible to do without but it is more complicated. Note: nothing prevents you from using JS together with PHP

  • Would you have an example of ? code already bundled with PHP.

  • Just put that code up there inside the tags <script> </script> before closing the tag <body> and trade #anuncio by your ad selector

  • didn’t work here..

  • If possible, add in question the code you tried

Show 1 more comment

Browser other questions tagged

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