0

Hello I have a problem when updating the "div", the refresh works well, however after the refresh when I click on the "div" which has just been updated I no longer have any reaction of my addEventListener javascript , why? and how to deal with this problem? thank you in advance.

here exemple onclick run perfect :

function updateDiv() { $( "#here" ).load(window.location.href + " #here" ); }

but after the function bellow won't run anymore:

document.getElementById("here").addEventListener("click", () => { alert(" hello world !") }

Reporter
  • 3,897
  • 5
  • 33
  • 47
isoparme
  • 11
  • 3

3 Answers3

0

try adding onclick event like this

function updateDiv() {  $("#here").load(window.location.href + " #here");
$("#here").attr("onclick","alert()");
}

function alert(){

alert(" hello world !");
}
0

Use setInterval() It may help you.

  • 1
    This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/low-quality-posts/31940504) – Zach Jensz Jun 04 '22 at 14:40
  • 3
    @ZachJensz I don't see how this is a covert comment. To me it attempts to answer the question, although it could use a little explanation. – Gert Arnold Jun 04 '22 at 15:04
-1

You can use passive event listener to keep them even if the element is created/destroyed/reloaded at runtime

function updateDiv() {  $("#here").load(window.location.href + " #here");}



$("#here").on("click", () => { alert(" hello world !") })
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="here">here</div>
<button onclick="updateDiv()">Click here</button>
Greedo
  • 3,438
  • 1
  • 13
  • 28