1

I have a .txt file called sample.txt, where I want to load some text and display it into my HTML document.

Here is my code:

<div id="test"></div>
document.getElementById('test').addEventListener("load", getText);
console.log("script loaded succesfully")
function getText(){
  fetch('sample.txt').then(function(data){
    console.log("hello")
    console.log(data.text);
  });
}

My issue is that the function getText, is not called on load, how can this be, when it logs out script loaded successfully?

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
Kristoffer Tølbøll
  • 3,157
  • 5
  • 34
  • 69
  • 6
    `load` event doesn't fire for regular elements. It's for `window` object. – Parth Thakkar Oct 03 '18 at 14:34
  • There are load events on plenty of elements including `img` and `iframe`, i.e. elements which trigger the *load* of external content. Divs don't load anything. – Quentin Oct 03 '18 at 14:41

1 Answers1

4

The proper way to call the load event it by attaching it to the window like :

window.addEventListener("load", getText);

I think to be sure that the DOM is loaded you could use DOMContentLoaded event instead :

document.addEventListener("DOMContentLoaded", getText);
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
  • He needs to listen when a file is loaded, not when the DOM is loaded. – Constantin Chirila Oct 03 '18 at 14:37
  • I don't think so @ConstantinChirila – Zakaria Acharki Oct 03 '18 at 14:38
  • @ConstantinChirila did you just assume my gender? – Kristoffer Tølbøll Oct 03 '18 at 14:43
  • I think @ZakariaAcharki is right because the "addEventListener" need to add the listener event first load and only at the second time to active the getText() function – tomer raitz Oct 03 '18 at 14:45
  • @ZakariaAcharki I'm kinda new to javascript and I was wondering would the DOMContentLoaded also work if where to put my script at the end of my body? Because wouldn't the DOM then already be loaded before the evenlistener is added and never trigger? (this is a hypothetical question I always put my scripts in the header but I was just wondering) – mrdeadsven Oct 03 '18 at 14:46
  • 1
    Hi @mrdeadsven _would the DOMContentLoaded also work if where to put my script at the end of my body?_ Yes it will work, but it may not necessary is such cases... – Zakaria Acharki Oct 03 '18 at 14:49