简体   繁体   中英

window.addEventListener works only after a refresh

I need a little help for one function which is working only after a refresh. I`m not experienced with javascript and i need just to add one small "div" to already compliled project.

The index.html is

... 
<body>
<script src="runtime-es2015-container.js" type="module">
<script src="runtime-es5-container.js" nomodule defer>
<script src="polyfils-es-5.js" defer>

<script>
 window.addEventListener("DOMContentLoaded", function() {
 setTimeout(() => {
   let envContainer = document.querySelector('.info');
   envContainer.setAttribute('style', 'flex-direction:column:');
   let envRow = document.createElement('div');
   envRow.classList.add('instance');
   envContainer.appendChild(envRow).innerText = 'some text ';
   },100);
 }
 ....

The functional is working only after refreshing the page. I gues the problem is with selecting the '.info', which is loaded before the function is executed.

Thanks, Svetoslav

I see you have some errors in the code, try using this code which i fixed and changed a little bit and let me know if it works

<script>
 window.addEventListener("load", function() {
 setTimeout(() => {
   let envContainer = document.querySelector('.info');
   envContainer.setAttribute('style', 'flex-direction:column');
   let envRow = document.createElement('div');
   envRow.classList.add('instance');
   envContainer.appendChild(envRow).innerText = 'some text ';
   },100);
 }
</script>

Just made a testrun of this and it seem to be working just fine, the only thing that was missing from your code was a ) in the end..

To me it looks like your problem is elsewhere. Well unless the info object is not created by code, then the problem is that it does not yet exist when you run this code..

--- Update ---
OKay so the div is created by js code and you have to wait for it.. the best idea I have is to poll and wait for it, I have updated the example to do just that and also changed to code to create the div after the first run of the function to simulate your situation.

 function update_info() { if(document.querySelector('.info')) { let envContainer = document.querySelector('.info'); envContainer.setAttribute('style', 'flex-direction:column:'); let envRow = document.createElement('div'); envRow.classList.add('instance'); envContainer.appendChild(envRow).innerText = 'some text '; } else { setTimeout(() => { update_info(); },100); } } window.addEventListener("DOMContentLoaded", function() { update_info(); const infodiv = document.createElement('div') infodiv.id = "info"; infodiv.classList.add("info") infodiv.innerHTML = "this first div"; document.body.appendChild(infodiv); })
 <body>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM