Search code examples
javascriptjquerysettimeoutaddeventlistenerpage-refresh

Why doesn't my page auto refresh properly?


My goal is to refresh the page when the class p.fancybox-error is visible, but I would like to know why this part of the code doesn't work at the top of my page.

<script type="text/JavaScript">
  var theDiv = document.querySelector("p.fancybox-error");
  theDiv.addEventListener("click", function() {
    setTimeout(function(){ location.reload(); }, 5000);
  });
</script>     

I put it under this line:

<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.4.min.js"></script>

But it gives me this error:

null is not an object (evaluating 'theDiv.addEventListener')

Thanks a lot guys, just take a look to @Stephane's answer, it works perfectly for me.


Solution

  • This polls every second looking for your class and auto-reloads when it exists

    $(function() {
      setInterval(function() {
        if($("p.fancybox-error").length) location.reload();
      }, 1000);
    });