Guide on obtaining an obscure style guideline in MS Edge using JavaScript

If you are looking to utilize the object-fit CSS rule, keep in mind that it is not supported in MSIE and MS Edge Browsers. While there are polyfills available for IE, none of them seem to work in Edge from my experience.

For instance, the polyfill fitie by Jonathan Neal works with IE but seems to fail in Edge (at least on the systems I've tested). This could be due to fitie relying on JS objects like element.currentStyle and element.runtimeStyle, which are no longer supported in Edge browsers. Using

window.getComputedStyle(element).getPropertyValue('object-fit')
doesn't return any value in Edge.

So how can one retrieve the value of the CSS rule object-fit using JavaScript in MS Edge browser?

img = document.getElementById('i');
s = self.getComputedStyle(img);
console.log('object-fit: ', s.getPropertyValue('object-fit'));
console.log('-ms-object-fit: ', s.getPropertyValue('-ms-object-fit'));
div {
  width: 400px;
  height: 320px;
  overflow: hidden;
}
#i {
  display: block;
  width: 100%;
  height: 100%;
  -ms-object-fit: cover;
  object-fit: cover;
}

div {
  box-sizing: border-box;
  border: 1px solid gold;
}
div,
p {
  font-family: sans-serif;
  font-size: 20px;
  width: 400px;
  margin: 0 auto;
}
<p>img: Has object-fit CSS rule, but does not appear in MS Edge JavaScript log</p>
<div>
<img src="https://dummyimage.com/640x240/333/444.png" id="i" />
</div>

Edit

There must be a way around this limitation since it's not completely ignored. The Developer Tools do show the rule underlined as expected.
https://i.sstatic.net/mAhYH.png


Bonus question:

Are there any polyfills available for object-fit that actually work in Edge?

Answer №1

You have the ability to directly reference it:

// 'Fill' in Chrome and undefined in Edge
console.log('object-fit',  
    window.getComputedStyle(document.querySelector('.test')).objectFit);

// 'rgb(255,0,0)' in both
console.log('color', 
    window.getComputedStyle(document.querySelector('.test')).color);
.test{ color: red; }
<div class="test">test</div>

The style property will return undefined in browsers that do not support it (such as Edge) even with a polyfill.

The issue lies in the fact that Edge does not recognize the object-fit rule when parsing the CSS, causing it to skip over it. Even if you try to shim the behavior with other properties or JavaScript, Edge remains unaware of it.

To specifically address the question "So how do I obtain the value of the CSS rule object-fit in MS Edge browser using JavaScript?" you can use

window.getComputedStyle(ele).objectFit
to retrieve the value, which will always be undefined (even after shimming).

Regarding the bonus question: background-size: cover is supported by Edge, allowing you to apply the image as a CSS background to a display:inline-block element and achieve the desired effect. You can easily replace the <img> with a styled <div>...

var img = document.querySelector('.i');

// If object-fit missing
if (!window.getComputedStyle(img).objectFit) {

  // Create a div
  var div = document.createElement('div');
  div.className = img.className;

  // Set the background image to be the source
  div.style.backgroundImage = 'url(' + img.src + ')';

  // Set background-size to the object-fit we want
  div.style.backgroundSize = 'cover';

  // Swap them
  img.parentNode.replaceChild(div, img);
}
.test {
  width: 400px;
  height: 320px;
  overflow: hidden;
  border: 1px solid red;
}

.i {
  display: block;
  width: 100%;
  height: 100%;
  object-fit: cover;
}
<div class="test">
  <img src="https://dummyimage.com/640x240/333/444.png" class="i" /></div>

This represents the basic concept - a shim like object-fit-images expands on this idea and supports additional properties like object-position.

Alternatively (with more HTML involved), you can retain the <img> tag and encase it in a container that emulates applying object-fit relative to it. This is the approach taken by object-fit-polyfill.

Both shims should function effectively in Edge.

Answer №2

I'm interested in utilizing the object-fit CSS rule.

To achieve an image covering its parent without needing to retrieve the value of the object-fit CSS rule with JavaScript in the MS Edge browser, you can take advantage of a solution that replicates the behavior of object-fit: cover using transform: translate and min-width/height properties.

Bonus: This method works seamlessly without the need for polyfills and is compatible across all browsers down to IE9.

Side note, MS Edge version 16 supports object-fit

Here's a code snippet that achieves the same effect as object-fit: cover by leveraging transform: translate and min-width/height:

div {
  width: 400px;
  height: 320px;
  box-sizing: border-box;
  border: 1px solid gold;
  margin: 0 auto;
  overflow: hidden;
}

#i {
  position: relative;
  display: block;
  min-width: 100%;
  min-height: 100%;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
}
<div>
  <img src="https://dummyimage.com/640x240/333/444.png" id="i" />
</div>


If desired, you can utilize CSS @supports to reset the aforementioned properties and incorporate object-fit:

div {
  width: 400px;
  height: 320px;
  box-sizing: border-box;
  border: 1px solid gold;
  margin: 0 auto;
  overflow: hidden;
}

#i {
  position: relative;
  display: block;
  min-width: 100%;
  min-height: 100%;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
}

@supports (object-fit: cover) {
  #i {
    min-width: auto;
    min-height: auto;
    top: auto;
    left: auto;
    transform: none;
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
}
<div>
  <img src="https://dummyimage.com/640x240/333/444.png" id="i" />
</div>


Another option to consider when dealing with images within a div element is to use inline style for the background-image property instead of an img tag.

In cases where a fixed-width/height div defines the boundaries for the image, this is a simple example of implementing that approach:

div {
  width: 400px;
  height: 320px;
  box-sizing: border-box;
  border: 1px solid gold;
  margin: 0 auto;
  overflow: hidden;
  background-position: center;
  background-size: cover;
}
<div style="background-image: url(https://dummyimage.com/640x240/333/444.png)">
</div>


Update:

You can also replicate object-fit: contain by adjusting the max-width and max-height properties:

div {
  width: 400px;
  height: 320px;
  box-sizing: border-box;
  border: 1px solid gold;
  margin: 0 auto;
  overflow: hidden;
}

#i {
  position: relative;
  display: block;
  max-width: 100%;
  max-height: 100%;                   
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
}
<div>
  <img src="https://dummyimage.com/640x240/333/444.png" id="i" />
</div>


Updated based on a comment

Simulating object-fit for videos can be more complex compared to images due to differences in how video elements behave. Various demos showcase different outcomes when mimicking cover or contain for videos.

To achieve consistent results similar to images, a script might be necessary to adjust the video's dimensions proportionally based on aspect ratios.

Additional resources and approaches for simulating backgrounds like object-fit are discussed in another Stack Overflow post: Simulate background-size:cover on <video> or <img>.


Another workaround involves utilizing media queries and max/min-aspect-ratio:

View Fiddle demo

Source:

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

Mastering VSCode IntelliSense: Unleashing the Power of Type Declarations

In my JavaScript projects, I aim to include TypeScript types sparingly to leverage IntelliSense for better code completions and receive warnings about type-related issues. To set up typechecking in JS, I created a jsconfig.json file and rely mostly on JSD ...

Efficiently map nested properties of this.props within the render method

When working in the render() method, I find myself passing numerous variables around. The recommended best practices suggest setting up variables before the return <div>...etc</div statement like this: const { products: mainProducts, ...

Utilizing the JSON.parse method in JavaScript in conjunction with an Ajax request while incorporating the escape character "\n" for new line functionality

https://jsbin.com/zuhatujoqo/1/edit?js,console Edit: json file has this line: {"pd":"ciao \\n ste"} I need to retrieve a valid JSON file through an ajax call. Then parse the result using JSON.parse. I'm confused about the behavior of t ...

Encountering a DOM exception with React 16.6 due to lazy loading/Susp

I am currently working on implementing dynamic import in my React application. Most of the React examples I have seen involve rendering the application to a specific tag and replacing its content, like this: ReactDOM.render(<App />, document.getEle ...

Response from the server to multiple asynchronous XMLHttpRequests

I'm in the process of creating a Web Application that involves making multiple simultaneous XHR calls using Ajax instead of native Javascript. $.ajax({ type: 'POST', url: 'Services/Service.asmx/MyFunction', contentTyp ...

Extract reference value from an HTML element

Is there a way to access the ref prop from an HTML element using Testing Library React? My current code snippet is as follows: it('element container ref should be null if prop noSwipe is passed', () => { const onCloseMock = jest.fn() ...

How to Convert JSON from an Object to a String using jQuery?

Currently, I am utilizing the Ajax Form jQuery plugin to fetch JSON data from a server: /** * A convenient function for the jQuery AJAX form plugin. */ function bindOnSuccess(form, callback) { form.ajaxForm({ dataType: 'json', ...

Encountering an issue while attempting to run a Node.js server on a Mac, receiving the error message "no appropriate image located."

unknown406c8f2d5ecb:proves airrider3$ node tronServer.js [Error: dlopen(/Users/airrider3/Documents/proves/node_modules/now/node_modules/node-proxy/build/Release/nodeproxy.node, 1): no suitable image found. Did find: /Users/airrider3/Documents/proves/n ...

instructions for ensuring gridview spans entire width of panel

I have a gridview that is contained within a panel. I am trying to make the gridview fill 100% of the width and height of the panel. This is what I've attempted so far: CSS .pnlGridView { position:relative; float:right; heig ...

When attempting to compress JavaScript with uglify-js, an unexpected token error occurs with the symbol ($)

When attempting to compress Bootstrap 4 js file using uglify-js, I encountered an error. The error message reads as follows: "Parse error at src\bootstrap\alert.js:1,7 import $ from 'jquery' ERROR: Unexpected token: name ($)". Now I am ...

Encountering the error "Cannot access property 'stroke' of undefined" when utilizing constructors in React and p5

Hi there, I'm having trouble with my React code and could really use some assistance. Being new to React, I'm trying to create a collision system between multiple bubbles in an array, but I keep running into this undefined error: https://i.sstat ...

What is the best method for choosing elements when I already possess a DOM element?

When you have a variable that contains a DOM element and need to select related elements, you can easily achieve this by wrapping it in a jQuery object. var myDomElement = document.getElementById("foo"); $(myDomElement ).find("a"); It is common for peopl ...

Adding a badge to a div in Angular 6: What you need to know!

How can I add a badge to a specific div in Angular 6? I have dynamic div elements in my HTML. I want to increase the counter for a specific div only, rather than increasing it for all divs at once. For example, I have five divs with IDs div1, div2, div3, ...

Converting javascript html object lowercase

Is there a way to dynamically adjust the height of specific letters in my label? Right now, I am overriding the text for the elements: let element = document.getElementById('xxx') element.textContent = 'Label' I attempted using <sup ...

Automatically compute and convert currency formats using JavaScript

May I ask again? Hopefully you understand. I am looking to automatically calculate with a money format. Here is a demo: https://jsfiddle.net/xp4ky2gg/ This is my code... HTML code <table style="width:100%"> ...

Displaying JavaScript values one by one using a for loop and alert

Having an issue with looping through a JSON array in JavaScript. I am trying to extract only SG_J1001 and SG_LS01, but it's not working as expected. The result is coming out like this [{"regis ....... var item = JSON.stringify(data['code'] ...

"I'm trying to incorporate react-datepicker into my ReScript application, but I'm struggling to

I am attempting to incorporate an external library like react-datepicker into my project. Below is the code snippet and how I am using it: module DatePicker = { @react.component @module("react-datepicker") external make: () => React.eleme ...

Looping through each combination of elements in a Map

I have a Map containing Shape objects with unique IDs assigned as keys. My goal is to loop through every pair of Shapes in the Map, ensuring that each pair is only processed once. While I am aware of options like forEach or for..of for looping, I'm s ...

how to set up automatic login for a user after changing their password using passport-local-mongoose

Trying to automatically log in a user, but encountering an issue with the current 'update' function that looks like this exports.update = async (req, res) => { const user = await User.findOne({ resetPasswordToken: req.params.token, re ...

Is it possible to utilize JavaScript for transmitting and storing data on a server?

Consider this scenario: When you submit a query on stackoverflow, the data you provide is entered into a text field. This information is then transmitted to the server for storage and eventual display to the user. Is it possible to code the functionality ...