Solution for problem with IE scrollWidth

Encountered a peculiar bug in IE where the scrollWidth is consistently off by 1px compared to the offsetWidth. This anomaly appears to be triggered by the length of text/characters within the element, specifically when overflow is set to something other than visible.

If you are curious about why I am cross-checking these values, refer to this question: HTML - how can I show tooltip ONLY when ellipsis is activated

To see an example of the issue, visit: http://jsfiddle.net/w5cwhjbf/2/

.base{
    font-size: 16px; 
    overflow: hidden;    
}

.wrapper{
    float: left;  
}
<div class="wrapper">
    <div id="div1" class="base">
        Why is my scrollWidth wrong in IE?
    </div>
</div>
<br style="clear: both;">
<br>
<button id="btn1" onclick="fnCheckScroll(div1,btn1)">Calculates Wrong</button>
<br>
<br>
<br> 
<div class="wrapper">
    <div id="div2" class="base">
        Why is my scrollWidth right in IE?
    </div>
</div>
<br style="clear: both;">
<br>
<button id="btn2" onclick="fnCheckScroll(div2,btn2)">Calculates Correctly</button>
<br>
<br>
<br>
The issue seems to stem from the character widths/font size resulting in what appears to be a fractional value that gets rounded up or down inconsistently. However, this does not cause scroll bars to appear (with overflow set to auto) and does not occur with overflow: visible.
        
<script type="text/javascript">
function fnCheckScroll(div, btn)
{    
   var iScrollWidth = div.scrollWidth;
   var iOffsetWidth = div.offsetWidth;
   var iDifference = iScrollWidth - iOffsetWidth;
   btn.innerHTML = ("Width: " + iOffsetWidth + "px  |  scrollWidth: " + iScrollWidth + "px  |  Difference: " + iDifference + "px"); 
}
</script>

In the example, despite having sufficient space for expansion, the first item's width is set 1px too short, or the reported scrollWidth is 1px too big. Additionally, no scrollbar is displayed (even with CSS set to overflow: auto), indicating that IE recognizes the lack of actual overflow within its code.

I'm interested to know your suggested fix or workaround for this random issue based on characters/font/font-size within the div?

Answer №1

Providing the optimal solution without understanding the specific issue related to this bug can be challenging. However, here are some approaches you could consider:

  • Implement a JavaScript bug-fix to modify attributes/styles if the two elements have varying sizes.

    if(iDifference != 0) { /* implement necessary adjustments */ }

  • Perform a tolerance check between the two elements; if the variance is within 2px, proceed with normal processing without concern.

    if(Math.abs(iDifference) <= 2) { /* no need for action here! */ }

  • Base all calculations on the outer element as it reflects the actual width of the container.

  • Rely on the inner element for computations to prevent any potential overlap with the outer element.

  • In case everything is functioning properly, consider leaving it unchanged - why fix something that is not broken?

The most suitable approach depends on your objectives and how the 1px gap impacts your workflow.

Answer №2

Discovered a viable solution for the issue that is compatible with ie9 and above. This workaround involves checking the width of the elements using getBoundingClientRect() along with scroll and offset width.

var boundingClientRectWidth = element.getBoundingClientRect().width;
var iScrollWidth = div.scrollWidth;
var iOffsetWidth = div.offsetWidth;

var amIOverflowing = (iScrollWidth > iOffsetWidth) && (boundingClientRectWidth == iOffsetWidth);

By verifying in IE whether the boundingClient has been set to the same size as the iOffsetWidth (without fractional width), we can avoid using an incorrect scroll width that rounds up instead of down, for example 273.36...

View this jsfiddle: http://jsfiddle.net/gskfke6L/1/

Answer №3

Adjust the padding-right property to 1px for the element with the class name .base.

.base{
    font-size: 16px; 
    overflow: hidden;
    padding-right: 1px;    
}

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

Adjusting the orientation of a vector worldwide using a quaternion in THREE.js

Is there a way to set the absolute global rotation of a vector using a quaternion? Imagine a function called f(v, q) which rotates vector v to quaternion q. While THREE.Vector3 has a .applyQuaternion function for applying rotations to vectors, this is a ...

Creating a new object in Typescript and populating it with default values based on a class

What is the best way to design a TypeScript class or JavaScript object that initializes with default properties? I am currently using TypeScript classes with parameters as shown below: Here is an example of my class: export class StateModel { stateID: ...

What is the best way to incorporate regular, light, and bold fonts into your project using links from Google Fonts

I am looking for three specific styles of Ubuntu font without having to download them. To access these fonts, I inserted this link in the <link href="https://fonts.googleapis.com/css?family=Ubuntu:300,400,700" rel="stylesheet"> According to Google& ...

Are there any images included in the WebResponse being downloaded?

I need to download HTML efficiently in order to parse it with minimal bandwidth consumption. Here is a snippet of my code: if (!String.IsNullOrEmpty(siteAddress)) webReq = WebRequest.Create(siteAddress) WebResponse webRes ...

Switch the placement of two DIV elements by their corresponding IDs

I am attempting to adjust the position of two divs using jQuery, but I seem to be a bit confused as they are already swapping positions. However, when they do swap, it results in a duplication of the field. I have tried using both insertBefore and insertA ...

When using Node.js, you may encounter the error message: "TypeError: brevo.ApiClient is not a constructor

My goal is to set up an automatic email sending system that, upon receiving details like name and email, will send a confirmation email to the provided email address with the message "subscribed." I've been working on this task for about 7 hours strai ...

The DOM lacks the assigned 'id' in the HTML

While working in the Moodle platform (version 3.5.7) using the Atto editor in both Chrome and Firefox, I have been attempting to assign an ID to a specific row class called "span9". My main goal is to give this element a unique ID and then reference it wit ...

Storing information in the concealed and interactive tabs within a tabview system

In my program, users are able to access groups through a left column list, similar to how Google Groups are displayed (seen in the image below). I would like the front-end to cache visited groups as users switch between them, so that when they revisit a g ...

Sliding Feature

Can someone assist me with implementing a jQuery half slide function from left to right? Please check out the following URL for more information: http://jsfiddle.net/prabunivas/Fy9Hs/2/ <div> <div id="col1" style="float:left"> &l ...

Is there a method to keep the leftmost column in a Google visualization table anchored in place when scrolling horizontally?

I want to replicate the typical google visualization table header row functionality, but I would like it to be focused on the first column instead. It doesn't appear to be a default feature, so I'm curious if it could be achieved using custom CSS ...

Oh no! There seems to be an unexpected token "<" in my React Native project on Visual Studio Code

When utilizing react-native in VS Code, I encounter an issue where my code fails to compile and throws a syntax error for the "<" symbol. Strangely, many tags work fine with "react-native run-android" from the Terminal. This is the code snippet that I ...

Show the result of file upload, whether it was successful or not, using ReactJS

I need to implement an Ajax call for uploading a file to the server. I want to display success and failure messages based on the outcome of the file upload process. $.ajax({ url: "https:my_url", data: {my data: my_data}, method : "POST", success: ...

Tips for altering CSS using the `:hover` pseudo-class

CSS Style for Navbar .navbar li { color: #B7B7B7; font-family: 'Montserrat', sans-serif; font-size: 14px; min-width: 70px; padding: 22px 16px 18px; } .navbar #menumain ul { width: 120%; } .navbar ul ul { display: none; } <div ...

Code for Custom Controllers in Strapi Beta version 3.0

I have encountered some discrepancies in the beta version of Strapi's controllers compared to the previous version. The new version includes multipart/sanitization boilerplate, and I am having trouble integrating my order object and Stripe charge. Be ...

Expandable Navigation Menu for Desktop Websites: Utilizing a Small Icon for a Full Width and Height Dropdown Menu upon Toggle Click (Utilizing Bootstrap 4)

Struggling to achieve a full-width and height display of my hamburger menu on toggle button click. I aim to have a hamburger with small icons on the left side of the screen, which, when clicked, should reveal a transparent full-width and height layout with ...

Is it possible to utilize the element tags from a different custom directive as the template for a new custom directive?

Recently started using angularjs and working on a web application that incorporates custom directives. I want users to have the ability to choose which directives they see upon logging in. To achieve this, I am storing the selected custom directive tags in ...

What is the best way to implement an Angular application within the child routes of another Angular application?

Is it possible to load an Angular app using lazy-loading (when a specific route is hit by users) into another Angular app without compiling the first one for use in the second? This is the Routing-Module of the app to nest into an Angular app: const upgr ...

Animating all the numbers on a jQuery countdown timer

http://jsfiddle.net/GNrUM/ The linked jsfiddle showcases a countdown of 2 seconds, with only the numbers displayed. My goal was to explore: a) How can I incorporate animations into the JavaScript code so that the number changes in size, color, and positi ...

Increasing the thickness of the border on a HTML table every two rows

I recently set up a table with 12 rows and 2 columns, containing various contents. I am looking to add borders to the table, but with a unique twist - after every set of 4 rows, I want to make the horizontal border thicker than usual. Does anyone know ho ...

Attempting to grasp the concept of ternary condition logic in this specific scenario

Recently, I delved into a code kata involving an array of football scores such as: ["3:1", "2:2"] (The total points here would be 4, 3 + 1) After applying certain rules and summing up the points, I came across an interesting solution: const points = g ...