Identifying flex-wrap capabilities across different browsers

Currently, I am developing a project that involves implementing a responsive grid using the flex wrap property. However, since my project needs to support IE9 and older versions of Firefox (version 28 and below), I am in need of a way to determine their support through JavaScript. So far, I have managed to identify IE9 browser using a conditional statement, but I am unsure how to detect older versions of Firefox using JavaScript. Can anyone provide guidance on this?

Answer №1

After much exploration, I have discovered the most straightforward approach:

var elementStyle = document.documentElement.style;
if (('flexWrap' in elementStyle) || ('WebkitFlexWrap' in elementStyle) || ('msFlexWrap' in elementStyle)){
  alert('Success!');
}

I also experimented with hasOwnProperty, but unfortunately it did not function correctly in IE and FF. So why rely on a bulky modernizr library when you can achieve the same result with just 3 lines of JavaScript?

Answer №2

Detecting CSS Properties

One way to detect a CSS property is by directly testing it on an element and checking if it returns undefined, as shown below:

element.style.<propertyName> != undefined
.

Simplest Approach (with some limitations)

The method mentioned above checks for the property directly and should work for most common properties, but not for all like flex-wrap.

function isStyleSupported(el, property) {
  return el.style[property] != undefined;
}
var testEl = document.getElementById('test');
testEl.innerHTML = (isStyleSupported(testEl, 'flexWrap')) ? "Flex Wrap is supported" : "Flex Wrap is NOT supported";
<div id="test"></div>

To enhance support and cover more properties, you can also check with DOM prefixes.

Enhanced Method for Better Support (including flex-wrap)

var domPrefixes = 'Webkit Moz O ms Khtml'.split(' ');

function toCamelCase(cssProp) {
  return cssProp.replace(/-([a-z])/gi, function(s, prop) {
    return prop.toUpperCase();
  });
}

function isStyleSupported(el, property) {
  if (el.style[toCamelCase(property)] != undefined) {
    return true; //supported
  }
  property = toCamelCase("-" + property);
  for (var i = 0; i < domPrefixes.length; i++) {
    if (el.style[domPrefixes[i] + property] !== undefined) {
      return true; //supported with dom prefix
    }
  }
}
var divEl = document.getElementById('result'), textEl = document.getElementById('textbox');
document.getElementById('checkSupport').onclick = function() {
  divEl.innerHTML = (isStyleSupported(divEl, textEl.value)) ? textEl.value + " is supported" : textEl.value + " is NOT supported";
};
<input type="text" id="textbox" value="flex-wrap" />
<button id="checkSupport">Check</button>
<div id="result"></div>

If you need to generalize this for various properties across different browsers, consider using modernizr for better coverage.

CSS.supports API

There is a new CSS API called CSS.supports which provides a boolean value to check if a specific CSS feature is supported by the browser. While this is a great option, older browsers may still require plugins like modernizr.

Conclusion:

For basic style detection, use

element.style.<property> != undefined
or consider including domPrefixes. If your needs are more complex, opt for modernizr for comprehensive feature detection.

Answer №3

Expanding further on @AndresTet's response, in case you are looking to avoid using a pre-built modernizr package, you have the option to craft your own customized version. Alternatively, you can extract and revamp the necessary flexbox tests from the existing resources, primarily focusing on:

function checkFeaturesAll(feature, prefixed, element) {

    var capitalizedFeature = feature.charAt(0).toUpperCase() + feature.slice(1),
        featuresList = (feature + ' ' + cssomPrefixes.join(capitalizedFeature + ' ') + capitalizedFeature).split(' ');

    if (is(prefixed, "string") || is(prefixed, "undefined")) {
        return checkFeatures(featuresList, prefixed);

    } else {
        featuresList = (feature + ' ' + (domPrefixes).join(capitalizedFeature + ' ') + capitalizedFeature).split(' ');
        return testDOMProps(featuresList, prefixed, element);
    }
}

tests['flexbox'] = function() {
    return checkFeaturesAll('flexWrap');
};

tests['flexboxlegacy'] = function() {
    return checkFeaturesAll('boxDirection');
};

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 audio directory is not included in the build of the Ionic framework, causing it to be skipped and absent

Recently, I've been working on an Ionic/Cordova app and came across a folder labeled /audio which consists of mp3 files: /www /assets /audio file.mp3 /css /js config.xml index.html The issue at hand is that the /audio directory is n ...

Failed XHR: POST request in Cordova encountered an error

I am currently using cordova to develop a mobile application that includes a basic login form. The issue arises when I input the wrong username and password, as I receive a response from the server stating "INVALID INFORMATION" in XML format. However, upon ...

Can Fullcalendar v2.6.0 be used with both jQuery-3.3.1 and MVC 5?

Can Fullcalendar v2.6.0 work with jQuery-3.3.1 and MVC 5? I have an older project that needs to be updated. Currently, I am using Visual Studio 2017 with jQuery-3.3.1, MVC 5.2.4, and moment.min.js 2.24 for recompilation. However, I keep encountering an err ...

Transitioning from the older version of Angular (1.0.8) to the newer version (1.2.0

Transitioning to the latest production version of Angular has been quite challenging for me. I have meticulously followed the migration guidelines, focusing mainly on the underscore prefix \ private attributes section that seemed relevant to my situa ...

Can you explain how to utilize prop values for setting attributes in styled-components v4 with TypeScript?

Overview Situation: const Link = styled.a` border: solid 1px black; border-radius: 5px; padding: 5px; margin: 10px 5px; `; type ButtonProps = React.ButtonHTMLAttributes<HTMLButtonElement>; const LinkAsButton = styled(Link).attrs<ButtonP ...

The system of jQuery Dialog UI is unable to recognize when the close icon is clicked

How can I detect if a user closes my dialog modal box using the 'X' button in the upper-right corner of the titlebar? I've been struggling to find a solution while using jQuery's Dialog UI plugin. Here is what I have tried so far: $(&a ...

React - The select component has received an invalid value of `undefined` that is out of range

I am working on a material-UI dialogue form that sends data to my API. One of the fields in the backend database is binary and only accepts two possible options. How can I handle this in the dialogue code provided below? Below is the error message: Mate ...

Using Javascript to Showcase a Video's Number of Views with Brightcove

How can I show the number of views for a video without using Brightcove's player? Brightcove Support shared this resource: , but I'm having trouble understanding it. ...

Communication between child and parent components in Vue.js is an essential feature

Attempting to invoke functions from my component to Vue for the login process. This is the code snippet of my component : Vue.component('auths', { data: function() { return { ip: '', sessiontoken: '' } ...

Experiencing difficulty incorporating JSON and JS into jQueryhandleRequestJSON and JS integration with jQuery

I'm having trouble fetching the 'sigla' field from a JSON file and inserting it into an HTML 'option object'. I could use some assistance with this issue, so if anyone out there can lend a hand, it would be much appreciated! Here ...

What is the method for invoking a function with arguments within an HTML `<p>` element?

I am looking to display like and dislike percentages on cards. <v-card v-if="software[2] == searched || searched == ''" class="software-card" > <h3>{{ software[2] }}</h3> ...

Every time Lodash.uniqueId is called, it consistently generates the value of

Consider using the lodash library, specifically version 4.17.11. _.uniqueId() seems to consistently output 1 instead of a random three-digit number. Similarly, _.uniqueId('prefix') always returns prefix1. Do you see this as a potential issue? ...

Integrate ruby code within a javascript string

I am looking to insert tfx-<%= @doc.doc[:b].metadata['filename']} %> into a JavaScript string called 'url' url = "<%= @document.doc[:a].url(response_content_disposition: ContentDisposition.attachment( [INSERT HERE] )) %>"; ...

Transform the API response from a string into an array containing multiple objects

How can I transform a string API response into an array of objects? When making a GET request, the result is returned as a single long string: const state = { strict: true, airports: [] }; const getters = { allAirports: (state) => state.ai ...

Incorporating PHP Variables into JQuery's Ajax Data

It's pretty obvious that I'm still getting the hang of jQuery. If you have any better suggestions for achieving what I'm trying to do, please feel free to share :) Here's the issue I'm facing. The script runs smoothly when you repl ...

Issue encountered while attempting to send a parameter in an Ajax request using jQuery

While utilizing ajax to invoke a function in my controller, I believe that I have correctly passed the parameters but am encountering an error. This is how my function looks in jQuery var user = $(this).data('user'); var idea = $(th ...

I am looking to retrieve data from the Graph API JSON and gradually refine my search to achieve successful

I am looking to retrieve data from the "fb_page_categories" endpoint, which provides an array of categories a page can be categorized under. The format for this request is as follows: GET graph.facebook.com /fb_page_categories? Once this request is mad ...

Retrieve data from an SQL database and populate an HTML dropdown menu in a web page using PHP

I am a beginner in the world of JavaScript and facing some challenges. I am working with PHP 7 and attempting to retrieve data from an SQL database, specifically a table. My goal is to extract a single column from this table and display it in a dropdown me ...

Commitments and incorporating items from an array into objects nested within a separate array

My current project involves a command line node application that scrapes valuable data from a specific website and stores it in a CSV file. For the scraping functionality, I am utilizing scrape-it, which enables me to successfully extract all the necessa ...

Reorganize child JSON objects into a new object that includes a parent ID

Exploring the realm of JavaScript, I am currently delving into Node.JS to interact with an API and save the data in a SQL Server. Utilizing the "request" and "mssql" Node packages for this task as they possess robust documentation and support. My query re ...