Adjusting the size of tables in raw JavaScript without altering their positioning

I am attempting to adjust the size of a th element without impacting the position of the next th in the row. Specifically, I want the width of the th to influence the width of the next th accordingly, rather than pushing it to the left.

Below is the code that I currently have:

(function () {
    var thElm;
    var startOffset;

    Array.prototype.forEach.call(
        document.querySelectorAll("table th"),
        function (th) {
            th.style.position = 'relative';

            var grip = document.createElement('div');
            grip.innerHTML = " ";
            grip.style.top = 0;
            grip.style.right = 0;
            grip.style.bottom = 0;
            grip.style.width = '5px';
            grip.style.position = 'absolute';
            grip.style.cursor = 'col-resize';
            grip.addEventListener('mousedown', function (e) {
                thElm = th;
                startOffset = th.offsetWidth - e.pageX;
            });

            th.appendChild(grip);
        });

    document.addEventListener('mousemove', function (e) {
        if (thElm) {
            thElm.style.width = startOffset + e.pageX + 'px';
        }
    });

    document.addEventListener('mouseup', function () {
        thElm = undefined;
    });
})();

A live demonstration of my code:

(function () {
    var thElm;
    var startOffset;

    Array.prototype.forEach.call(
        document.querySelectorAll("table th"),
        function (th) {
            th.style.position = 'relative';

            var grip = document.createElement('div');
            grip.innerHTML = " ";
            grip.style.top = 0;
            grip.style.right = 0;
            grip.style.bottom = 0;
            grip.style.width = '5px';
            grip.style.position = 'absolute';
            grip.style.cursor = 'col-resize';
            grip.addEventListener('mousedown', function (e) {
                thElm = th;
                startOffset = th.offsetWidth - e.pageX;
            });

            th.appendChild(grip);
        });

    document.addEventListener('mousemove', function (e) {
        if (thElm) {
            thElm.style.width = startOffset + e.pageX + 'px';
        }
    });

    document.addEventListener('mouseup', function () {
        thElm = undefined;
    });
})();
table {
    table-layout: fixed;
    width: 100px;
    border-width: 1px;
    border-style: solid;
    border-color: black;
    border-collapse: collapse;
    overflow-x: auto;
}

table tr {
  box-sizing: content-box;
}

table th {
    height: 50px;
    width: 20px;
    border-width: 1px;
    border-style: solid;
    border-color: black;
    box-sizing: border-box;
    user-select: none;
}
<table>
    <thead>
        <tr style="width: 100%;">
            <th style="width: 300px">th 1</th>
            <th style="width: 150px">th 2</th>
            ... // More th elements with varying widths
        </tr>
    </thead>
</table>

Visit this CodePen link for a demo

Thank you!

Answer №1

Hello everyone, I have successfully resolved the issue and here is the code snippet that solved it:

makeResizable() {
let startOffset;

let columnHeaders = this.container.querySelectorAll("th");

for(let i = 0; i < columnHeaders.length; i++) {
  let currentHeader = columnHeaders[i];
  currentHeader.style.position = 'relative';

  let grip = document.createElement('div');
  grip.innerHTML = "&nbsp;";
  grip.style.top = 0;
  grip.style.right = 0;
  grip.style.bottom = 0;
  grip.style.width = '5px';
  grip.style.position = 'absolute';
  grip.style.cursor = 'col-resize';

  currentHeader.appendChild(grip);

  EventManager.on(grip, 'mousedown', (e)=> {
    let nextColumn = columnHeaders[i + 1];
    let currentHeader = columnHeaders[i];
    let originalNextColumnWidth = nextColumn.getBoundingClientRect().width;
    let originalCurrentColumnWidth = currentHeader.getBoundingClientRect().width;

    startOffset = currentHeader.offsetWidth - e.pageX;


    EventManager.on(document.body, 'mousemove', (e)=> {

      // Adjust widths based on mouse movement
      if (currentHeader) {
        currentHeader.style.width = startOffset + e.pageX + 'px';

        let offset = originalCurrentColumnWidth - currentHeader.getBoundingClientRect().width;
        nextColumn.style.width = (originalNextColumnWidth + offset) + 'px';

      }
    });
  });

  EventManager.on(document.body, 'mouseup', (e)=> {
    EventManager.off(document.body, 'mousemove');
    currentHeader = null;
  });
}

}

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

The color of the SVG is not visible in the PNG rendition

I have applied a style to an svg image and successfully changed the fill color using a random colors function in JavaScript. However, when I convert the svg to a png format after making these color changes, the PNG file retains the original colors instead ...

How is it that when a function is called with just one parameter, it ends up receiving the entire element?

In my table, I have various item numbers listed with corresponding quantity input fields identified by id="itemNumber". Each line also includes a button that triggers a function (onclick="addItemAndQuantity(itemNumber)") to retrieve inf ...

Struggling to interpret JSON data from an AJAX call using jQuery in a Python/Flask application

Currently, I am attempting to analyze a POST request sent via AJAX using jQuery in a python script. The structure of the request is as follows: request.js function get_form_data($form){ var unindexed_array = $form.serializeArray(); var indexed_ar ...

Tips for choosing an <li> element with JavaScript

<style> .sys_spec_text{} .sys_spec_text li{ float:left; height:28px; position:relative; margin:2px 6px 2px 0; outline:none;} .sys_spec_text li a{ color: #db0401; height:24px; padding:1px 6px; border:1px solid #ccc; background:#fff; dis ...

Fade background when the youtube video in the iframe begins playing

Hey there! I'm looking to create a cool effect on my (wordpress) site where the background dims when a YouTube video starts playing. The video is embedded in this way: <iframe frameborder="0" width="660" height="371" allowfullscreen="" src="https ...

React.Children does not reveal the presence of any offspring

I am looking to implement react-native-maps-clustering in my project. However, this library only accepts markers that are direct children of the maps component. An example of how it should be structured: <MapView> <Marker/> <Marker/> ...

Error: It is not possible to access the 'map' property of an undefined value 0.1

I'm currently experimenting with React.js and I encountered an error that's giving me trouble. I can't seem to pinpoint the root cause of this issue. Shout out to everyone helping out with errors: TypeError: Cannot read property 'map ...

Struggling with Mocha, supertest, and passport when testing authenticated routes with JWT authentication

I've been experimenting with testing authenticated routes in Mocha, but I've run into an issue where the user created in the `before` or `beforeEach` hooks doesn't persist. Here's a snippet from my test.js: const should = require(&apo ...

What could have caused my javascript file to disappear from npm?

After creating a small library consisting of a .js file with commonly used functions, I placed it in the node_modules directory alongside my other packages. Everything seemed to be going well. A few days later, I decided to add a new package using npm ins ...

Programming in Python often involves utilizing a combination of powerful libraries such as BeautifulSoup,

I am currently developing a program that is designed to extract emails and collect specific links from them, particularly those from Newegg. I have successfully used iMAP to log in and access the HTML content of the emails. However, I am encountering an is ...

Nextjs is having trouble loading the Infogram script

Struggling to insert an Infogram into my project by pasting the script but it's not working as expected. All other scripts in _app.js are functioning properly, however, this particular script isn't loading the graphic even though it appears when ...

Overriding PrimeNG styles with Bootstrap _reboot.scss

I'm facing an issue where Bootstrap is overriding my PrimeNG styles, particularly with its _reboot.scss file. I have included the relevant parts where I referenced it in both my styles.scss and angular.json files. Interestingly, I noticed that this is ...

Employ an asynchronous immediately-invoked function expression within the callback

Can an asynchronous IIFE be used inside the callback function to avoid the error message "Promise returned in function argument where a void return was expected"? You can find an example here. signIn(email: string, password: string, course?: ICourse): ...

Building nested components with Vue.js involves creating a complex routing structure within the architecture

Utilizing vue.js for my administration app, I aim to create a highly modular UI architecture. Therefore, I have structured and enclosed the Header, Body, Sidebar, and Main in single file components as illustrated below. Tree App - Header - dynamic cont ...

AngularJS login form with JSON data

I am currently learning Angular and focusing on the login form implementation. The specific model I am working with can be found in this PLNKR. There are two challenges that I am struggling to resolve. Issue 1: I'm trying to figure out how to tur ...

Limit search to retrieve specific items based on pointer in JavaScript using Parse.com

BlogApp.Collections.Blogs = Parse.Collection.extend({ model: BlogApp.Models.Blog, query: (new Parse.Query(BlogApp.Models.Blog)).equalTo("author", "xMQR0A1Us6").descending('createdAt').limit(9) }); The code snippet above doesn't seem ...

Using JavaScript to place markers on a Google Map may encounter an issue with a for

Close to solving a three-day challenge. Currently working on placing markers on a Google Map using latitudes and longitudes stored in a Django model. This is my first time using AJAX, but I'm giving it a shot to make this work. Firebug is pointing out ...

Inaccurate sizing of popup dialogs on SharePoint 2010

Currently, I am in the process of revamping a SharePoint 2007 web application to SharePoint 2010. I was surprised to find that the popup dialog boxes for new items, edit, etc. have inline styles for fixed width and height. Below is an example where div.ms ...

Adjusting the screen width to activate a responsive nav bar with a centered title

I'm facing an issue with the alignment of the heading within a navigation bar, causing the links to wrap before the collapse of the nav-bar occurs - https://i.sstatic.net/bKyPM.png I am trying to make the links collapse earlier than they currently d ...

Having trouble retrieving data about my marker through react-leaflet

Hello, I am currently working on accessing information about my marker using React and react-leaflet, which is a library based on Leaflet. I initially tried to utilize useRef, but unfortunately it did not provide the expected results. When attempting to us ...