What is the best way to adjust a CSS width using the output from a JavaScript function?

I am facing a challenge with a GridView within a div wrapper. The row headers along the left side need to always be visible. So far, this setup is working fine. However, I need the wrapper to have a variable width to adjust to the browser size.

Although I have managed to determine the desired width of the wrapper based on the browser width using Javascript, I am struggling to set this width as the wrapper.width. It is not necessary for the wrapper width to update after the page loads or monitor browser resizing.

Here is a rough diagram:

|   |column headers      |
| R |--------------|      
| O | gridview data      |
| W |              |      
|   |  this part         |
| H |  will scroll |<--->
| E |  while the         |
| A |  Row headers |
| D |  stay there        |
| E |              |
| R |______________      |
| S | scroll bar   |

Here is the ASP code snippet:

<pseudocode>
 <table>
   <tr><td>row headers</td>
       <td><div class="Wrapper">
              <asp:GridView>dataBind()</asp:gridview>
       </div></td></tr>
 </table>
</pseudocode>

CSS:

div.Wrapper 
{
 width:800px;<--this needs to change based on the browser width
 overflow: auto;
}

Javascript:

var Width = window.innerWidth - 275 || document.body.clientWidth - 275

I am looking for a solution to set the wrapper.width = Width or any alternative method to achieve the same result. Any assistance would be greatly appreciated.

I have attempted using a percentage for the width, but it did not utilize the browser window as 100%, instead, it took the percentage of the full width of the GridView, which did not meet my requirement.

Thank you in advance for your help.

Edit: included additional code

<script type="text/javascript">
    var Width = window.innerWidth - 275 || document.body.clientWidth - 275;
    var divElement = document.getElementById("wrappist");
<!--I tried a few different things at this point, here are a couple of them-->
    divElement.offsetWidth = "80px";
    divElement.style.width = Width.toString() + 'px'; 
</script>

<div runat="server" id="wrappist" class="Wrapper">
  <asp:GridView runat="server" ID="ALPGrid" CssClass="Grid"
       CellPadding="5" GridLines="Both" AutoGenerateColumns="false"
       OnRowDataBound="ALP_RowDataBound" OnRowCreated="ALP_RowCreated"
       DataKeyNames="ItemID">
  <HeaderStyle CssClass="GridHeader" />
  <RowStyle CssClass="Row" />
  <columns>column stuff in here</columns>
  </asp:GridView>
</div>

Answer №1

Give this a shot:

const newWidth = window.innerWidth - 275 || document.body.clientWidth - 275;
const element = document.getElementById('divId');
element.style.width = newWidth.toString() + 'px';

Additional note: This code snippet adjusts the width of the div element directly on the HTML element, thereby overriding any existing style rules from external CSS files.

Answer №2

What do you think about using a CSS-only approach?

<div class="container">
<div class="header"></div>
<div class="content"></div>
</div>

The CSS styling

.container
{
width:700px;
}
.header
{
float:left;
width:150px;
height:250px;
background-color:#444;
padding-bottom:20px;
}
.content
{
margin-left:150px;
height:250px;
padding-bottom:20px;
background-color:#eee;
overflow:auto;
}

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

Working with Variables in JavaScript and PHP Scripting Languages

I have a PHP script that displays all the folders (categories) on my website: echo "<ul>"; foreach(glob('category/*', GLOB_ONLYDIR) as $dir) { $dir = str_replace('category/', '', $dir); echo '& ...

Unexpected behavior detected with vue.js

I'm having some trouble with my vue.js code. When I try to run this example, the output in the browser is showing "product" instead of "Boots". <div id="app"> <h2>{{product}}</h2> </div> <script src="https://unpkg.com/& ...

Looking to eliminate curly braces from a string?

Despite my efforts to search through the site, I am still unable to resolve the issue at hand. var blah2 = JSON.stringify({foo: 123, bar: <x><y></y></x>, baz: 123}); This is what I attempted: blah2.replace(/[{}]/g, ""); Here&apo ...

How to loop through a list variable using Razor syntax in an HTML document

Exploring the world of asp .net and MVC is a new adventure for me. I have delved into a service method named Jumbo(), which delivers a list consisting of first names, last names, and contact numbers. In my main project, I invoke this method in the followin ...

Tips for positioning Bootstrap form labels and input fields in alignment

Currently, I am enhancing bootstrap-4 forms that consist of multiple input fields and labels. The form is functional, but I aim to elevate its visual appeal and user-friendliness. Working Snippet <link rel="stylesheet" href="https://stackpath.bootst ...

Execute a JavaScript function when an element loaded via Ajax in a Spring MVC framework triggers the onChange event

I currently have a dropdown list with two values and I am looking to enable or disable four components based on the user's selection. If the user picks the first value, the components should be enabled, otherwise they should be disabled. On the main ...

Update Refresh Token within Interceptor prior to sending request

I'm stuck on this problem and could use some guidance. My goal is to refresh a user's access token when it is close to expiration. The authService.isUserLoggedIn() function returns a promise that checks if the user is logged in. If not, the user ...

The code for the Express app.get() method on the server is not being updated, although other parts of the

Recently, I encountered an issue with my node js and express server that is running on localhost. I made a change in the server code from: app.get('/', (req, res) => { res.sendFile(__dirname + '/public/index.html'); }); To: app. ...

The BackgroundWorker isn't triggering as scheduled due to a lengthy await period

After running smoothly for a few hours, the code suddenly stops before starting up again. This cycle continues intermittently... This project involves a web application with WCF service that is hosted on IIS. The BackgroundWorker (BGW) is initiated when t ...

Is it possible to submit a form through a JavaScript hotkey?

Here's the current code that I'm working with: <select tabindex="2" id="resolvedformsel" name="resolved"> <option selected="selected" value="yes">resolved</option> <option value="no">not resolved</option> ...

problem with accessing a website input area

Upon clicking outside the "subheader", I need to display the words "register" and "login" again, unless something is typed into the input fields... that's all there is to it, just click outside the subheader $(document).ready(function() { $(&ap ...

How can I access a directory using ASP.NET on the server?

Is there a way to open a folder location from the code behind? Process prc = new Process(); prc.StartInfo.UseShellExecute = true; prc.StartInfo.FileName = @"\\Shared\FolderName\test"; p ...

Unable to verify the provided resource: Mailchimp

Welcome everyone to my first question posted on StackOverflow. I have tried my best to provide all the necessary details regarding the issue in order to seek assistance. If you require additional information, feel free to ask. To give a brief overview, I ...

Trapped in the Web of Facebook OAuth

I've been struggling with this issue for a day now and I can't seem to pinpoint where I'm going wrong. I have experience working with JavaScript on the client side and recently started following a book tutorial. However, it appears that Face ...

The submitHandler for AJAX does not function properly when using bootstrapvalidator

I'm encountering an issue with the Bootstrap validation tool found at https://github.com/nghuuphuoc/bootstrapvalidator The submitHandler function seems to be malfunctioning for me. Upon form submission, the entry is not being created and the form rel ...

Move the button to the following line and center it. Ensure that the background image remains at full size

.home{ background-image:url("https://cdn.pixabay.com/photo/2016/12/27/21/03/lone-tree-1934897_960_720.jpg"); background-repeat: no-repeat; height: 100vh; display: flex; align-items: center; justify-content: center; } .hero-text{ fon ...

Is it possible to use display:grid with a parent element set to a height of 100%

Why doesn't the display:grid property stretch my content to the height of this column? The HTML structure row - col-6 is created using Bootstrap. I am aware that I can manually set a specific height for the parent container, but I would prefer not to ...

Using the transform property with the scale function causes elements positioned in the bottom right corner to vanish

Issue specific to Google Chrome and Windows 10 I'm currently working on a flipbook that adjusts content size using transform:scale() based on the user's screen size. There is also a zoom feature that allows users to adjust the scale factor. I ha ...

Difficulty with spacing in HTML/CSS styling

Here is what I'm currently working on: link to jsfiddle code * { margin: 0; padding: 0; } html { height: 100%; } header, nav, section, article, aside, footer { display: block; } body { font: 12px/18px Arial, Tahoma, Verdana, sans- ...

The CSS of the Sendgrid template is being overlooked

I have utilized Sendgrid to create the template mentioned below: https://i.sstatic.net/TFQfl.png In order to send this template using my Node server, I have developed the module provided in the code snippet: /* * Created by root on 6/6/16. */ var path ...