Lately, I've been trying to simplify things by consolidating my JavaScript functions into one file instead of using multiple separate files. The idea was to merge all the functions together and wrap each one in its own function so that they can be easily called using function()
without the need to switch between files. The first two effects worked perfectly, but when I tried wrapping the third section, I encountered an error:
Uncaught TypeError: Cannot read property 'style' of null
Upon further investigation, I realized that I had forgotten to include
<div class="colors"></div>
in the HTML file. To fix this, I added it dynamically when the function was called using document.getElementsByClassName('top').innerHTML = '<div class="colors"></div>';
. Unfortunately, this solution didn't work as expected, causing all the sections to load simultaneously when the page loads. Here's a snippet of my JS code:
// JavaScript code
// Function to handle form inputs and adjust styles accordingly
function sections(){
function callback(e) {
var emptyInputs = [];
for (var n = inputs.length; n--;) {
if (!inputs[n].value.length) {
emptyInputs.push(inputs[n]);
}
}
var totalEmpty = emptyInputs.length;
var totalInputs = inputs.length;
var topSections = document.querySelectorAll(".top");
for (var o = topSections.length; o--;) {
topSections[o].style.width = 100 - totalEmpty / totalInputs * 100 + "%";
}
}
var forms = document.querySelectorAll(".form"),
inputs = [];
for (var i = forms.length; i--;) {
var elements = forms[i].querySelectorAll("input, textarea, select");
for (var j = elements.length; j--;) {
if (elements[j].type != "button" && elements[j].type != "submit") {
inputs.push(elements[j]);
elements[j].addEventListener("input", callback, false);
}
}
}
// Additional functionality to generate CSS gradients
function generateCSSGradient(colors) {
var l = colors.length, i;
for( i=0; i<l; i++) {
colors[i] = colors[i].join(" ");
}
return "linear-gradient( to right, "+ colors.join(", ") + ")";
}
// Define gradient color stops
var predefinedColors = [
["#1ABC9C","0%"],
["#1ABC9C","33.3%"],
["#EC7063","33.3%"],
["#EC7063","66.6%"],
["#3498DB","66.6%"],
["#3498DB","100%"]
];
// Apply generated gradient to specified element
document.querySelector(".colors").style.background = generateCSSGradient(predefinedColors);
document.getElementsByClassName('top').innerHTML = '<div class="colors"></div>';
var windowWidth = window.innerWidth + "px";
document.querySelector(".colors").style.width = windowWidth;
};
In addition, I included some custom CSS to define the width and height properties:
.colors{
width: 100%;
height: 4px;
}
I'm struggling to figure out why this issue is occurring. You can check out a demo of the problem here, and also view one of my working demos with individual JS files here. Any assistance would be greatly appreciated.