Ways to generate multiple elements using JavaScript

Is there a way to dynamically freeze columns in a table as I scroll it horizontally? I've achieved this statically using JavaScript, but is there a way to indicate the number of columns and achieve the desired style?

This is what my JavaScript code currently looks like:

var styles =`
 // CSS styles for freezing first two columns in a table
`;
// Dynamically create and append a <style> element with the specified styles
var styleSheet = document.createElement("style")
styleSheet.innerText = styles
document.head.appendChild(styleSheet)

Instead of manually adding nth-child every time, is it possible to automate this process with a JavaScript function?

Answer №1

Organize your data values into an array:

const styles = 
` table:first-of-type thead tr th:first-child{
    position: sticky;
    position: -webkit-sticky;
 background-color:white;
color:crimson;
      left: 0px;
   z-index: 3;
  
}

table:first-of-type tbody tr td:first-child{
    position: sticky;
    position: -webkit-sticky;
    background: crimson;

    left: 0px;
color:black;
   z-index: 1;
  
  
}`

 + [30, 138].map((leftValue, index) => 

`
table:first-of-type thead tr th:nth-child(${index+2}){
    position: sticky;
    position: -webkit-sticky;
    color: black;
          left: 30px;
      z-index: 3;
}

table:first-of-type tbody tr td:nth-child(${index+2}){
    position: sticky;
    position: -webkit-sticky;
    background: black;
      left: ${leftValue}px;    
   z-index: 1;
}
`);

$('pre').text(styles);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<pre></pre>

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

Switch button for updating text, icon, and displaying search bar

Having trouble with a header and navigation bar setup. The goal is to have a search button that toggles between "Search" and "Close Search" when clicked, while also opening the search bar below the navigation. I've experimented with different methods ...

Tips for displaying dynamic content in VueJS?

I'm currently working on an app that allows users to choose which type of vuetify element they want to display on the page. There are 4 options available for selection. My goal is to render the corresponding vuetify component when a user clicks on the ...

My API is feeding data to the Material UI CardMedia image

Has anyone encountered a similar error while using the CardMedia API provided by Material-UI? I am currently utilizing the Card & CardMedia components from material-ui to display data fetched from an api. However, I am facing difficulty in displaying ...

Unlocking the intricacies of navigating through nested arrays of objects in JavaScript

I need help figuring out how to loop through a nested array of objects in my code. I've tried different approaches but can't seem to grasp how it works. The object data I have looks like this: [ { "restaurantName":"Bron ...

Angular has the ability to round numbers to the nearest integer using a pipe

How do we round a number to the nearest dollar or integer? For example, rounding 2729999.61 would result in 2730000. Is there a method in Angular template that can achieve this using the number pipe? Such as using | number or | number : '1.2-2' ...

Tips for accessing the names of subdirectories and files on a website

If we have the URL, is it possible to access the names of the files within the parent directory? Similar to how we can do in DOS by using the command "DIR" to view the list of files inside a folder. For example, if we have a URL like , I am curious to kno ...

After using promise.all, I successfully obtained an array of links. Now, how do I calculate the total number of links in the array?

function verifyAndTallyURLs(linksArray) { let validations = linksArray.map((link) =>{ return fetch(link) .then((response) => { return { webpageURL: response.url, status: response.status, ...

Prevent background image animation in CSS

I've encountered an issue with a simple button I created that uses two background images for normal and hover states. Upon testing in various browsers, I noticed that the images animate on hover, causing them to slide up and down. I tried eliminating ...

Optimizing JavaScript performance by packaging files with Browserify

Currently, I am utilizing AngularJS for the front end of my project. Initially, I was using Grunt as my build tool but now I am interested in transitioning to npm for this purpose. I came across a useful link that discusses using npm scripts as a build too ...

Can the image upload file size be customized or adjusted?

Recently, I've come across a standard input file code that looks like this: <Label class="custom-file-upload"> <input type="file" onChange={onDrop} /> Upload Photo </Label> I have been thinking about limiting the size of the ...

Transform HTML into PNG with Canvas2image, followed by the conversion of PNG into BMP

Is there a direct way to convert HTML to BMP? After searching online, it seems that there isn't a straightforward method. So, I decided to convert HTML to PNG using canvas JS and then use PHP to convert the file from PNG to BMP. I have a question abou ...

Updating JQuery function after window is resized

click here Currently, I am using slick-slider to showcase content in 3 columns by utilizing flexbox. The aim is to have the slider activated only on mobile view. This means that when the screen size shrinks down to mobile view, the 3 column flexbox transf ...

Transmit data to a modal using JSX mapping technique

When working with a map that renders multiple items, how can I efficiently pass parameters like the item's name and ID to a modal component? render(){ return( <div> <Modal isOpen={this.state.OpenDel ...

The button is positioned at the bottom right within a div surrounded by text that flows around it seamlessly

Image Is there a way to position a button in the bottom right corner of a div with a fixed height that is filled with text where the text flows around the button? I have attempted using "float" and positioning the button, but I have not had any success. ...

How about mixing up your backgrounds with an overlay effect for a unique look?

Hey there, I'm currently working on adding random backgrounds to my website through an overlay, but I've hit a roadblock when it comes to displaying them. Here is the code I'm working with: .css / .php #intro { background: ...

In Angular, you can easily modify and refresh an array item that is sourced from a JSON file by following these steps

Currently, I am working on implementing an edit functionality that will update the object by adding new data and deleting the old data upon updating. Specifically, I am focusing on editing and updating only the comments$. Although I am able to retrieve th ...

How can we enhance the efficiency of rendering text on the screen?

Imagine having a <p> tag inside a <div> with specific properties: div { height: 100px; width: 100px; overflow: hidden; } My goal is to continuously add words to the <p> tag until an overflow is detected, meaning stop when the f ...

Stop the div from expanding because of oversize text in Bootstrap

I have the following HTML source code for a Bootstrap card: <div class="card shadow-none card-fluid mb-3 mb-md-5"> <div class="row"> <div class="col-md-3 col-lg-3 mb-3 mb-sm-0"> <img class="img-fluid rounded" ...

Update the input type on the fly

Hey there, I've got a bit of an unusual question. I'm looking to create a form with fields that vary for each user, like a text input or a checkbox. I attempted using Angular to achieve this: <div ng-controller="myCtrl" ng-repeat="x in prova" ...