Problem with inserting columns (Vue/Javascript function) into Bootstrap row: for loop malfunctioning

I'm currently working on a function to insert columns into a Bootstrap row using Vue/javascript. However, I've hit a roadblock with the second part of the process, which involves inserting child nodes. No matter where I place the index in the loop, it doesn't seem to work. I've tried multiple approaches without success. The goal is to insert a swatch into the row and subsequent columns thereafter. The first swatch insertion works fine. The columns are set to col-md-3 for 4 across. The code snippet below shows that the statement works for the first insertion but fails at the next stage.

// Conditional statement to check if swatch exists before insertion


 let swatch = document.querySelector('.row');
 let element = document.getElementById("bg-gradient");
 // If it isn't "undefined" and it isn't "null", then it exists.
 if (typeof(element) != 'undefined' && element != null) {
   let i;
   swatch = document.querySelector('.row').children[i];
   for (i = 0; i < swatch.length[0]; i++) {
     swatch[i].appendChild(newSwatch);
     gradDiv.style.backgroundImage = gradient;
     textDiv.innerHTML = `<h5>${hexValues}</h5><p>${hexValues}</p>`;
   }
 } else {
   // First swatch in first row.
   swatch.appendChild(newSwatch);
   gradDiv.style.backgroundImage = gradient;
   textDiv.innerHTML = `<h5>${hexValues}</h5><p>${hexValues}</p>`;
 }

https://i.sstatic.net/EAl5r.jpg

HTML before swatches, into an empty row:

<div class="container-fluid bg-3 text-center">
  <h3>Your Gradients</h3><br>
  <div class="row">
 </div>
  </div>

With swatch added 

<div class="container-fluid bg-3 text-center">
  <h3>Your Gradients</h3><br>
  <div class="row">
  <div class="col-md-3">
  <div id="bg-gradient">

  </div>
  <div id="info">

  </div>
</div>
 </div>
  </div>

To resolve the issue with the loop not inserting the swatches in each subsequent col-md-3 position, one solution could be to test if the id "bg-gradient" exists in an if statement, as this id corresponds to the div containing the actual gradient. This might be a more efficient approach than using a for loop. What would be the best way to test for the existence of the id #bg-gradient? Any suggestions or tips are greatly appreciated!

https://github.com/xhostcom/vue-gradient-swatch-generator.git

Thank you in advance for any advice or guidance.

Answer №1

I apologize for the inconvenience, but further details are still required. Is your intention to construct HTML similar to the following example?

<div class="container-fluid bg-3 text-center">
 <h3>Your Gradients</h3><br>
 <div class="row">
  <!-- swatch #1 -->
  <div class="col-md-3">
   <div id="bg-gradient">...</div>
  </div>
  <!-- swatch #2 -->
  <div class="col-md-3">
   <div id="bg-gradient">...</div>
  </div>
  <!-- swatch #3 -->
  <div class="col-md-3">
   <div id="bg-gradient">...</div>
  </div>
  <!-- swatch #4 -->
  <div class="col-md-3">
   <div id="bg-gradient">...</div>
  </div>
 </div>
 <div class="row">
  <!-- swatch #5 -->
  <div class="col-md-3">
   <div id="bg-gradient">...</div>
  </div>
  ... additional swatches ...
 </div>
</div>

By utilizing a Bootstrap grid, this structure will generate a color swatch layout as demonstrated below:

#########################################
# Color 1 # Color 2 # Color 3 # Color 4 #
#########################################
# Color 5 # Color 6 # Color 7 # Color 8 #
#########################################

If you simplify the process by adding the newSwatch element to this layout, does it achieve the desired outcome?

let swatch = document.querySelector('.row');
swatch.appendChild(newSwatch);
gradDiv.style.backgroundImage = gradient;
textDiv.innerHTML = '<h5>${hexValues}</h5><p>${hexValues}</p>';

In my interpretation, there seems to be no necessity to verify the presence of an element with the id = bg-gradient since it is included in the new swatch being added.

Answer №2

After some tinkering, I managed to resolve the issue without needing a loop. All it took was including a conditional statement in the saveSwatch function.

// Conditional statement to check if swatch exists before insertion
      let swatch = document.querySelector('.row');
      let element = document.getElementById("bg-gradient");
      //If it isn't "undefined" and it isn't "null", then it exists.
      if(typeof(element) != 'undefined' && element != null) {
        swatch.appendChild(newSwatch);
        gradDiv.style.backgroundImage = gradient;
        textDiv.innerHTML = `<h5>${hexValues}</h5><p>${hexValues}</p>`;
        } else {
        // First swatch in first row.
        swatch.appendChild(newSwatch);
        gradDiv.style.backgroundImage = gradient;
        textDiv.innerHTML = `<h5>${hexValues}</h5><p>${hexValues}</p>`;
       }
    },

This method effectively adds both initial and subsequent swatches.

One issue remains with empty rows inserting blank values. My attempt at a checkSwatch function hasn't succeeded yet, as shown below:

 checkSwatch() {
        let swatch = document.querySelector('.row');
          if(swatch.children <= 0) {
             console.log("Check Swatch Still  Works")
          }
        console.log("Check Swatch Works")
    },
      saveSwatch() {
         this.checkSwatch()
      console.log("Save Works");
      this.createSwatch();
    },

I'm struggling to get the condition right to prevent insertion when no gradient is set.

It was challenging to see the solution amidst the complexity of the problem! Since every swatch is considered a child of the target div (a bootstrap row), there's no need for looping through children since they're all initially empty. Just a simple check to avoid inserting an empty column without any content such as the gradient.

Any advice or suggestions are appreciated.

Thank you!

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

Having trouble accessing NWJS modules with your new windows?

When I create a window using window.open in my NWJS application, it appears that the window is unable to access any nodejs or nwjs modules. How can I find a solution for this issue? I utilize document.write to add content to the page because the content m ...

Typing a Character Automatically Focuses on Input Field

I have a situation where I want to focus on an input field when the user presses the '/' key. The issue is that once the element is focused, it automatically adds the '/' key to the input field because of how the detection is set up. do ...

The sequence of JQuery ajax and promise chaining

My current situation involves a jQuery AJAX call with an optional then: var ajax = $.get({ /* params */ }).done(function(request) { // success handling. no explicit return, so return undefined }).fail(function(jqxhr, textStatus, error) { // failure ha ...

Hold off on moving forward until the content has been loaded using ajax within loops

I am facing an issue with waiting for ajax requests to complete before proceeding. My task involves iterating through all the options in five select lists. Upon selecting an option in "Select1", it dynamically loads or refreshes "Select2". The same proces ...

Utilizing util.format to enclose every string within an array with double quotation marks

Currently .. var utility = require("utility"); var carsInput = 'toyota,chevrolet'; var cars = carsInput.split(','); var queryString = utility.format('Cars: [%s]', cars); console.log(queryString); // Cars: [toyota,chevrolet] ...

Utilizing PUG for Iterating Through Multiple Items in Express Framework using JSON Data

I'm currently working on a small application using Express and PUG, aiming to achieve the following: https://i.stack.imgur.com/ZDyTK.png index.pug ul#restaurants-list li img.restaurant-img(alt='Mission Chinese Food', sr ...

Images of significant size displayed on websites appear distorted when viewed on mobile devices

I am currently working on a web application that specializes in storing and showcasing satellite images based on specific locations. One issue I have encountered is the large file size of these images, which can be up to 20MB in jpg format, leading to ren ...

Issue with Nuxt 3 and .nojekyll file not being effective on Github Pages

I am facing some challenges while attempting to deploy my nuxt project on a github page. I have included the .nojekyll file in the public folder, but even after running generate, files with "_" are still showing up under public/static. https://i.sstatic ...

Determining when a function is triggered from the JavaScript console

Is there a way to conceal a function in JavaScript console so that it's inaccessible for calling? Let me give you some context - let's say I have a JavaScript function that adds records to a database using Ajax. The issue is, anyone can call thi ...

What is the preferred method for logging out: using window.location.replace('/') or setting window.location.href to window.location.origin?

When it comes to a logout button, which is the better option: window.location.replace('/') or window.location.href=window.location.origin? Can you explain the difference between these two methods? It's my understanding that both of them remo ...

The API has been triggered twice

I am currently working on a React component where I have implemented an API call using the useEffect hook with an empty dependency array. However, I noticed that the API is being called twice and I can't seem to find the reason behind it. import { use ...

Encountering a Reference Error with Google following the installation of vue-google-autocomplete

I am currently working with vue.js and Laravel 5.6.12 I found a helpful guide on installing vue.js google autocomplete on this GitHub page. Here are the step-by-step instructions I have followed: npm install vue-google-autocomplete --save Next, I added ...

Update all project files in Firebase authentication

A client-side project is being developed using firebase and vue. After a successful login by the user, the authService object gets updated in the Login component, but not in the router. The authService is utilized in both the Login component and AdminNavba ...

Dynamic resizing of charts in Angular using ChartJS

I am currently working on a stacked bar data chart using Chart.js 2.0.2 and Angular-Chart 1.0.0 to display some information. My goal is to identify when the user reaches the bottom of the chart container, so that I can dynamically add more data while maint ...

Switching left navigation in material-ui when the user interacts within the application boundary

I am currently implementing a toggle feature in my AppBar to display the LeftNav. I have successfully set it up to close when the toggle is clicked again. However, I wish to mimic the behavior of most left nav bars where clicking anywhere outside of the ...

How does handleChange receive the value as an input?

Greetings! Currently, I am delving into the world of React and JavaScript. I am experimenting with a Table Component demo that can be found at the following link: https://codesandbox.io/s/hier2?file=/demo.js:5301-5317 In the demo, there is a function defi ...

A guide to updating property values in an array of objects in JavaScript while ensuring they remain in consecutive order

I am dealing with an array of objects called list. The parameters rid and rorder are provided for processing. -> 1. Whenever the value of rid matches the id in the list, the itemorder is updated with the value of rorder. -> 2. In the updated list p ...

The React Js issue of excessive re-renders occurs when the number of renders surpasses the set limit to prevent infinite loops in the application

I attempted to develop a feature that includes: 2 input boxes - one for key, one for value An array that stores values from the input boxes when a button is clicked Displaying the array in a list To achieve this, I created a React Js component: import ...

Best practices for securing string values in Node.js

Looking to retrieve the IP address with nodejs/express. Check out the code snippet below that accomplishes this: const ipAddress = String(req.ip || "unknown"); Considering that req.ip is pulled from an HTTP header, there's a potential risk ...

Using React to Dynamically Display JSON Data as HTML

Struggling to incorporate HTML rendering from JSON data into my React component without relying on dangerouslySetInnerHTML. I want to include other React components within the rendered HTML, but facing challenges when trying to render multiple elements or ...