Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
97 views
in Technique[技术] by (71.8m points)

Moved nav html code to separate file, javascript not working now

My navbar was fully working with the hamburger icon to animate out using the javascript file until I decided to move the nav code to a separate file so I could load it to all different html documents. Now when I try to click on the burger icon I receive the error below. The code still loads the nav bar (logo, icon, formatting) except the javascript doesn't work because it says the value of getElementById is null. Don't know how to fix it.

IMAGE OF CURRENT ERROR FOLDER WITH TEXT FILES OF ALL THE CODE

question from:https://stackoverflow.com/questions/65838759/moved-nav-html-code-to-separate-file-javascript-not-working-now

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your code runs before the .load() function can return anything. It runs asynchronously to stop blocking other code from running. You can feed a callback function to the load function which will be called when the load function returns. Then the DOM will be updated to know your nav elements. You can encapsulate your other code in a function and just put that function name as an argument or you can pass an anonymous function and just put all the stuff in there on the spot.

Example:

$('#nav-placeholder').load('assets/nav.html', function() {
    const ham = document.getElementById('ham');
    ham.addEventListener...
    ...
    ..
    .
 });


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...