+ 3

"<div class="img"></div> " won't show when scrolling. I have this error: Cannot read property 'classList' of null

Here's the link to my code: https://code.sololearn.com/Ww0BdBlh8WeJ

21st Dec 2018, 10:49 PM
noUseForAName
noUseForAName - avatar
8 Réponses
+ 6
One way of curing is: Change your line 45 from img.classList = ''; to img.classList = 'img'; Otherwise the querySelector will return null once you scrolled a little bit because there does not exist the DOM with class img anymore. https://code.sololearn.com/Wo0evwRYEwr8/?ref=app
21st Dec 2018, 11:02 PM
Gordon
Gordon - avatar
+ 4
Second way of curing is: 1. Declaring the DOM variable in global context 2. Moving your querySelector to a function added to load listener of window. Demo: https://code.sololearn.com/W69wf6gKIe90/?ref=app In this way, it is ensure that the getElement will be carried out once at the beginning only, when the DOM with class name img is still there. Note that : the image will not be shown again with this method. Because your image is attached to the img class.
21st Dec 2018, 11:11 PM
Gordon
Gordon - avatar
+ 3
Thanks, Kougaiji. For the second way, although you have not used, it involves the concept of closure. When you have time, here is David Carroll's pick of 3 readings from beginner to advanced: https://www.sololearn.com/post/45261/?ref=app
22nd Dec 2018, 12:11 AM
Gordon
Gordon - avatar
+ 2
Thank you very much for solving this Gordon! A very simple solution yet so hard for me to find out lol. Thanks again!
21st Dec 2018, 11:42 PM
noUseForAName
noUseForAName - avatar
+ 2
You are welcome, Kougaji. And right, you inspire me, I should also teach you how to find out the problems. We add console.log in between the lines to help us understand the values of variables in intermediate states. https://code.sololearn.com/WuBzocc861ZK/?ref=app Adding console.log in your original version, we can see that actually the DOM is got successfully in its first attempt. P. S. I think this is very useful for most SoloLearners. If you don't mind, I'll use this copied code of yours as a demo of how to apply console log in debugging for later Q&A questions. Can I?
21st Dec 2018, 11:49 PM
Gordon
Gordon - avatar
+ 2
Sure go ahead! It would of great help to fellow SoloLearners. Thanks a lot!
21st Dec 2018, 11:59 PM
noUseForAName
noUseForAName - avatar
+ 2
That's strange, I just tried again, and all the links work
22nd Dec 2018, 12:59 AM
Gordon
Gordon - avatar
+ 1
I'd like to read them but the link is not working...
22nd Dec 2018, 12:57 AM
noUseForAName
noUseForAName - avatar