Issue
Reworking some old code for a project i need to resubmit and wrote this almost 6 months ago so i cant even remember much and i struggle with JS.
I have a onclick function that adds the class current to my html, it is a popup message for a user and when they click exit it removes the popup button, But looking now in my console it is give out an error of script.js:13 Uncaught TypeError: Cannot set properties of null (setting 'onclick') at script.js:13:19
This code does work fine but i cant have console errors for my project.
This is the javascript function that adds and removes the class current.
const quizStart = document.querySelector('.quiz-btn');
const quizPopup = document.querySelector('.start-quiz-popup');
const quizMain = document.querySelector('.main');
const quizExit = document.querySelector('.exit-btn');
// Add current tag for onclick targetting
quizStart.onclick = () => {
quizPopup.classList.add('current');
quizMain.classList.add('current');
};
// Remove current tag for onclick targetting
quizExit.onclick = () => {
quizPopup.classList.remove('current');
quizMain.classList.remove('current');
};
The popup is set to have opacity of 0 and then when the current tag is added to the class, another css element of .main.current has opacity to 1.
Before
<section class="main"></section>
<div class="start-quiz-popup"></div
After
<section class="main current"></section>
<div class="start-quiz-popup current"></div
I have looked at other guides and asked a couple people but they are not to sure, I struggle with javascript alot and not sure what is wrong when its working fine. This is a old project that i need to completly rework and have had to make alot of changes and more to come, html and css are fine but looks like i need to rewrite alot of css as originally followed a guide and was all built on one page, but it had 0 responsivness as i didnt know how to do all of that with the way it was setup.
It probably is very basic code but i just cant figure it out or what the best way to go about making a updated version. I have tried a couple examples but it just replaces my current tag in place rather than adding the "current" tag maybe the word "active" would be better so future i'll use thaat, just need to get it working without a console error. Apoligies if this is so simple, im just stuck.
Solution
Where exactly have you imported your script?
If the script has been imported at the top of the HTML without the async
or defer
attribute, it will instantly start executing before the HTML is parsed and rendered, therefore causing the above error.
Check your script import.
Answered By - Shreyas Salankimatt
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.