1

Hello fellow developers,

I have a simple question. I'm working on my javascript skills, which are obviously not the best :). I'm trying to code a search box with the giphy API, by tutorial. My code was working to 100% like the code displayed in the tutorial until video 5, but now (video 6) it's not working anymore.

I'm getting the error "Uncaught TypeError: Cannot read property 'addEventListener' of null". I googled a lot and tried the fixes which I found here, but they are not working on my code :/ The funny part of this is, that my code is working on codepen.io! So the only difference between codepen and my local website, are multiple search forms and bootstrap. So I'm guessing the problem are multiple search forms, because of this lines:

const searchGif = document.getElementById("search-gif");
const searchInput = document.getElementById("gif-search-string"); 
searchGif.addEventListener('submit', function(event){
   event.preventDefault();
   const query = searchInput.value;
   search(query);
})

But I thought because I'm grabbing the right form by ID before I execute the rest of my javascript code, it is ok? So I hope that you can help me to resolve my problem. Like I said, I'm not very good in JS and just trying to get better and better <3.

PS: loading my script by script tag at the end of the html body PS2: Here is my complete HTML Code -> index.php - timeline-gif.php

  • How do you load your js into the page? Script tag? Please add your html head to the question. – sandrooco Sep 14 '20 at 08:24
  • @ the end of my body tag –  Sep 14 '20 at 08:30
  • I am quite sure that your `searchGif` is assigned before the element itself is created/rendered. To wait for this to happen see this: https://stackoverflow.com/a/9899701/5243272 Codepen wraps the user's code automatically which probably is the reason that it works there. – sandrooco Sep 14 '20 at 08:32
  • But this is exactly the same way i'am doing right now? First: LOAD HTML THEN JS? I dont see the difference :( –  Sep 14 '20 at 08:49

1 Answers1

0

It's how you "start" your code. Loaded !== rendered (not 100% sure that these are the correct terms). Try to wrap it in a self executing function:

(function() {
 // Put your code here - dom should be available
})();
sandrooco
  • 4,955
  • 6
  • 29
  • 69
  • I was trying this already because its a solution in the posts which are linked in the main topic on top. But its not working :( I'll get 2 errors then not just one. –  Sep 14 '20 at 13:38
  • the same error, but no on 2 different lines. ( first like the example on top and the second error on the line where I close the function (end of the script) –  Sep 14 '20 at 13:51
  • Then I think you'll have to post your whole html. Hard to reproduce otherwise. – sandrooco Sep 14 '20 at 14:16
  • [index.php](https://codepen.io/mauricewoitzyk-ger/pen/abNKKzB) - [timeline-gif.php](https://codepen.io/mauricewoitzyk-ger/pen/poyKKJz) –  Sep 14 '20 at 15:35