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

I am currently working on adjusting the first two columns of the table, but I am encountering some issues with

I have successfully fixed the first 2 columns of a table, but now there is an extra row showing up in the table header. .headcol { position:absolute; width:7em; top:auto; left: 0px; } .headcol2 { position:absolute; width:15em; top:auto ...

ViewCheck and every

Can IsInView be set to wait for all elements with the same class, instead of calling them individually? For instance, if there are three sections, can they be called like this: $(".section").on('inview', function(event, isInView) { i ...

Code functions properly on local host but encounters errors when deployed to live server

My comment system was working fine on localhost using PHP, AJAX and JavaScript. However, after transferring my website to a live server, the code does not seem to be functioning properly. Here is an example of the script: <script type="text/javascript ...

The second AJAX request isn't functioning properly; it should only be executed once the first one has successfully completed

I am experiencing an issue with my ajax calls. The second call should only be triggered after the first one is successful. However, even though the first call always returns success, I keep getting an error for the second one. function proceedWithUnlock(t ...

Identifying changes in value in any scenario, jQuery

When I click on a button and change the input value, I want an alert to display 'Ok Done', but it's not working as expected. The input value may contain both numbers and letters. $("#myTextBox").bind("change paste keyup", function() { ...

Utilizing Ajax to serialize or transfer JSON objects

I have received a Json object and I am looking to extract the data using JavaScript. Specifically, I need help with looping through fields and extracting the data. def For_Sale_Listing(request,id): try: listing = Listing.objects.filter(pk=id) ...

Incorporating additional ES6 modules during the development process

As I build a React component, I find that it relies on an ES6 component that I'm currently developing. Since I created the latter first, what is the typical method to include it during development as I work on the second component? If the dependency w ...

How can I use the store command to retrieve the href value of a link using a css selector in Selenium?

Is there a way to store a URL from a link using CSS instead of xpath? store //tr[td[contains(.,'6 Day')]][1]/td[8]/a@href my_var open $my_var If so, how can I achieve this goal with css? I managed to use the following locator: store css= ...

Include a character in a tube using Angular

Hey everyone, I have a pipe that currently returns each word with the first letter uppercase and the rest lowercase. It also removes any non-English characters from the value. I'm trying to figure out how to add the ':' character so it will ...

Is it possible to display a variety of color schemes in just one console.log()?

My task involves working with an array of hexadecimal values, "colors": ["#d5dd90","#e6bb45","#ef9770"] To log these out in different colors, I used the following method: colors.forEach((value)=>{ console.log(& ...

Eliminate border around image

I've been trying to get rid of the image border using different methods img { border: 0px; } I even attempted to remove it from the browser console with this code border: none !important This is what my html code looks like <div id="startD ...

Having trouble retrieving an object from an event handler in ReactJS

const question = { quest : "What is my age?", answers : [16,15,21,30], correct : 21, } validateAnswer(){ let usersResponse = document.getElementById('ans-1').textContent; let response = this.question.correct; if(usersResp ...

Retrieve the value of a DOM element within the document.ready function

After researching, I discovered a way to make my textArea resize when the page is fully loaded. $(document).ready(function() { // Handler for .ready() called. }); I decided to test it out and inserted the following code into the function: $(document). ...

Error encountered in onclick handler due to unterminated string literal in PHP and jQuery

Trying to utilize PHP to send variables into the onclick of an element is resulting in an "Unterminated string literal" error due to long strings. Below is a snippet of my PHP code: $query = $conn->prepare("SELECT Name, Image, Description, Link, Price, ...

Tips on uploading information from a PDF document onto a website

My goal is to develop a program or script that can extract data from PDF form fields and automatically input it into the corresponding textfields on my website, all done through the front end. The problem I'm facing is not knowing where to begin with ...

Here is a helpful guide on updating dropdown values in real time by retrieving data from an SQL database

This feature allows users to select a package category from a dropdown menu. For example, selecting "Unifi" will display only Unifi packages, while selecting "Streamyx" will show only Streamyx packages. However, if I first select Unifi and then change to S ...

Use the powerful $.post() method to transfer an image to another page seamlessly

I have two pages, the first page contains a form where users can enter information such as name and mobile number. Additionally, they can upload an image. I would like to use jQuery to access the uploaded image and send it to another page using the $.post( ...

The reverse animation for .is-exiting in Smoothstate.js is not triggering

I've been searching for a solution to my issue but haven't had any luck finding one that works for me. Currently, I am using smoothstate.js to trigger animations when the page loads and ideally reverse them when the page exits. However, while th ...

An unexpected error occurred with React JS stating: "Parse Error: Line 27: Unexpected token . at http://localhost/PHP-React-Demo/ajax_call.html return {cell.data.row}"

I need help in showing data from a database in a React JS application. Encountered error in React JS: Error: Parse Error: Line 27: Unexpected token . at http://localhost/PHP-React-Demo/ajax_call.html return {cell.data.row} This is my code: Index.p ...

Inline-block divs styled with CSS3 are causing a white gap to appear at the top of

I have been searching for solutions to my problem, but I can't seem to find one that works. My goal is to create two columns that each take up 50% of the screen width. However, I am facing an issue where there is a gap at the top that I cannot seem t ...