Segment will expand completely upon inserting a new division

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.

Answer №1

Your gradient design consists of a nested structure with a div containing another div. The inner div holds the color while the outer one limits the width. You are adjusting the width dynamically, but there is a slight difference between your two versions that is unrelated to the provided code ;-)

.top {
  overflow: hidden;
}

The reason why your colored strip is visible from the beginning is due to this specific CSS rule. Make sure to include it in your updated version to resolve the issue.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ensuring Bootstrap 3 Table Header Widths Remain Fixed

How can I ensure the header columns in my Bootstrap 3 table maintain a fixed width, regardless of the content in the regular rows? I want to avoid the messy look of content splitting onto multiple lines. Here's an example: I'd prefer not to adju ...

Detecting modifications to an array with MobX

Today marks my first foray into learning MobX and I am eager to discover how to track all array changes (insertions, deletions, etc) with MobX. A practical example would definitely help clarify this: const TodoList = ({todos}) => ( <ul> ...

Scrolling through four limited list items automatically

Hey there! I am currently working on a design project. You can check it out here. I'm trying to replicate a section from another site, which you can see here. <div class="latest-winners-container"> <h3 class="header">Latest Winners< ...

Using CSS to align a <li> element in the center

Do you have a question? I am trying to center a menu using the <li> tag, and I also have two buttons. .subiectele-zilei { width:100%; padding-left: 25px; overflow:hidden; padding-bottom:8px; background-color:#f5f5f5; margin ...

Why using $refs in interpolation fails and leads to errors in Vue.js 2.x components

Here is a codepen I created: codepen const sidebar = { name: "sidebar", template: "<p>SIDEBAR</p>", data() { return { active: true }; }, methods: { test() { alert("test: " + this.active) } } }; new Vue ...

Error detected in Deno project's tsconfig.json file, spreading into other project files - yet code executes without issues?

I am working on a Deno project and need to utilize the ES2019 flatMap() method on an array. To do this, I have created a tsconfig.json file with the following configuration: { "compilerOptions": { "target": "es5", ...

What is the best method to eliminate the 2px flaws on the right edge?

Issue only observed on small screens using Android Chrome (Nexus 5x, Nexus 6) with Android 5+. Cannot replicate problem on a Nexus 4. Utilizing basic bootstrap setup and angular; unsure if related. Experiencing artifacts up to 2px wide on the right side o ...

Exploring the ins and outs of utilizing pseudo selectors with material-ui

I've been attempting to accomplish a simple task. I wanted to toggle the visibility of my <TreeMenu/> component in material UI v1 using pseudo selectors, but for some reason it's not working. Here is the code: CSS: root: { ba ...

"Mastering the art of text animation: A beginner's guide

If you want to see a cool moving text animation, simply head over to this link: . The text will automatically type out and then clear just like the example below: Ever wondered how to create this kind of text animation? Any language can be used - React, A ...

Expanding the foundation of the HTML problem

I have my main page located at index.html and I am trying to transfer my template to base.html. In the index.html file, I used {% extends 'base.html' %}, but it is showing an error of *Unresolved template reference ''base.html'&apo ...

Three divs arranged side by side with responsive design for mobile viewing

This code generates 3 divs for display. However, I am looking to optimize them for mobile devices. What steps can I take to accomplish this? Currently, the divs are oriented to the left and are not visible on a mobile device. I would like them to display ...

Adding supplementary documents within the app.asar file via electron

This is a Vue application using electron-builder. { "scripts": { "serve": "vue-cli-service serve", "build": "vue-cli-service build", "electron:build": "vue-cli-service electron:build", "electron:serve": "vue-cli-service electron:serve", ...

When I navigate to the About page in Vue, the data is automatically cleared

Assist me, please! I am encountering an issue with my website. I have two main pages: Home and About, as well as a component called SecondPage. The SecondPage component contains two tables filled with data that should be displayed on the About page. Howeve ...

Generating elements added at various depths within an HTML document with the help of JavaScript

create_new.append("div") .append("form").merge(update_5) .attr("action", d => d.market) .attr("target","_blank") .style("width","100%") .style("height","282") .append("input").merge(update_5) .attr("type","submit") ...

Exploring the use of Rails and jQuery to automatically update data through the use of setTimeout and ajax calls

There's a specific page accessible in the browser at "/calendar" that directs to "calendar#index". Utilizing a javascript setTimeout function, I'm attempting to re-fetch and update data on my page using $.get ajax method. $.get("<%= calendar ...

Is browserHistory.push ineffective in react.js?

I am currently working on a React ecommerce website. I have encountered an issue in the login component where, upon clicking the submit button on the form, the system is supposed to check if the user is authenticated using useEffect. If the user is authent ...

Is it possible to integrate a Twitter bootstrap theme into a Rails 4 application if the Vendor/assets directory is missing?

My goal is to integrate a theme from wrapbootstrap.com into my rails 4.1 application. After creating a new app with rails 4 scaffolding, I proceeded to extract the downloaded zip directory which contains 4 directories and an index.html file. I then placed ...

Leverage the power of getServerSideProps when working with Dynamic Routes

I have been working on implementing getServerSideProps in my file named [username].js which utilizes dynamic routing. Next.js requires the use of both getStaticPaths() and getStaticProps({ params }) for dynamic routing. However, there seems to be an issu ...

Discord.js version 13 encountered an issue where it is unable to access properties of undefined while

Having trouble with creating a warn system that just won't work! I've tried various solutions but nothing seems to be fixing it. Would greatly appreciate any help! Error Log: [FATAL] Possibly Unhandled Rejection at: Promise Promise { <reje ...