window.onload and window.onbeforeunload | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

window.onload and window.onbeforeunload

Why I have to use window.onload to run this code and why if I put window.onbeforeunload = function () {alert("Wait")} image-slider stops working? https://code.sololearn.com/WQ7iM3i5PF5j/?ref=app

9th Dec 2018, 11:20 PM
evgeniy_pp
evgeniy_pp - avatar
4 Answers
+ 2
Your question contains two parts: A) Why window.onload? A1) You can consider the following demo an endorsement to ShortCode's answer: https://code.sololearn.com/WriFNOoR188j/?ref=app A2) There are two more ways: A2. 1) putting the JS scripts at end of body. A2. 2) define function main then onload = main B) onbeforeunload fails because your browser bans spammy script.
10th Dec 2018, 2:40 AM
Gordon
Gordon - avatar
+ 4
Because If your window hasnt load, your Element returns null. var myImg = document.getElementById("curImg"); document.getElementById("btnPrev").addEventListener("click", goPrev); document.getElementById("btnNext").addEventListener("click", goNext);
10th Dec 2018, 12:33 AM
ShortCode
+ 1
Glad that we are of help ☺️ Please try these out. Am looking forward to seeing your codes in hot today 😉
10th Dec 2018, 5:40 AM
Gordon
Gordon - avatar
0
Thank you for your answers. It's really helpful, especially this post: https://www.sololearn.com/Discuss/1546397/?ref=app
10th Dec 2018, 5:36 AM
evgeniy_pp
evgeniy_pp - avatar