My JavaScript Function is not connecting well with my HTML or CSS because its saying that it (Cannot read properties of null (read 'style')
.
this is the error on VS Code.
error screenshot
I was hoping this would work out in my favor because it is my first time trying something this complex so far. But I’m assuming I have forgotten some kind of loop or not connected my JS to the document well.
Here are the sources for the HTML and CSS I would love for someone to help me out with this bug.
I have been trying to re-work the syntax since that is what the error describes but I feel this might be a deeper issue involving the rest of how I have set the script up.
I have also tried to look up this error on here before this but it is all either outdated or not quite the exact problem I am facing.
<!DOCTYPE html>
<html>
<head>
<title>java script testing</title>
<link rel="stylesheet" herf="new.css">
<script>
var showing = true;
function checkforshow() {
if (showing = true) {
showing = false;
} else {
showing = true;
}
}
if (showing = true) {
document.getElementsByTagName("h1").style.opacity = "0";
} else {
document.getElementsByTagName("h1").style.opacity = "1";
}
</script>
</head>
<body>
<button onclick="checkforshow()">Hide Ele</button>
<h1>Blah Blah</h1>
</body>
</html>
2
Answers
I think this is what you wanted to do.
First we declare our boolean in false because the title is already visible.
Second we declare the function and we get inside of it the title by its id.
Based on the previous value of the boolean we change the display.
Finally we assign showing to be (not showing).
If this is not what you wanted please let me know 🙂
The problem in the code is that there are typos and logic errors in the "checkforshow()" function and the code sequence that follows it.
First, in the if condition inside the function, instead of comparing whether "showing" is equal to true, the expression is assigning the value true to the variable "showing". The expression would be correct:
Also, even if the condition were fixed, the "showing" variable is set to "true" at the beginning of the code, but it is never updated after the function is executed, so the code sequence below the if will never be executed.
To fix this, you can call the "checkforshow()" function when the button is clicked and update the opacity of the "h1" element based on the value of the "showing" variable. Also, there is a typo in the "link" tag of the header, where "href" was typed as "herf".
Below is the corrected code:
Now, when the button is clicked, the "checkforshow()" function is called, the "showing" variable is updated, and the "updateOpacity()" function is called to update the opacity of element "h1" based on the current value of "showing".