How can i restart the page, if the user closes an annoucment?

I’ve tried to implement the function, that if someone closes an specific annoucment that it automatically refreshes the site.

Here is the code which I have tried to solve it:

document.addEventListener('DOMContentLoaded', function () { const closeButton = document.querySelector('name of annoucment'); closeButton.addEventListener(‘click’, function () {
console.log(‘Button clicked’);
location.reload(); }); });

The problem is, that sometimes it works perfectly fine and sometimes it doesnt work at all. Does someone know how to solve this problem?