Detecting the preferential usage of -webkit-calc instead of calc through JavaScript feature detection

While it's commonly advised to use feature detection over browser detection in JavaScript, sometimes specific scenarios call for the latter. An example of this can be seen with jQuery 1.9's removal of $.browser.

Despite the general recommendation against browser detection, I find myself facing a situation where I need to dynamically calculate the number of available "slots" in a JS layout. This calculation is done using calc(100%/{0}), where {0} represents the number of slots.

In the case of iPads, setting the height with .css("height", "calc(100%/3)") will lead to failure since it requires the use of -webkit- prefix.

Given this scenario, could someone guide me on how to implement feature detection instead of relying on outdated methods like $.browser.webkit?

Answer №1

Begin by creating a dummy element and inserting it into the document. Then, apply the following code:

.cssText.height = 'calc(100px - 50px);'
. Finally, check if the element's height matches the expected value. Repeat this process for each vendor prefix.

It may be helpful to explore Modernizr's source code for similar feature detection scripts, like those found in calc.js.


While Modernizr can detect the presence of features, it does not provide information on which prefix to use. The snippet below demonstrates how to determine the correct prefix:

var calc = (function(){
    var dummy = document.createElement('div');
    var props = ['calc', '-webkit-calc', '-moz-calc', '-o-calc'];
    for (var i=0; i<props.length; ++i) {
        var prop = props[i];
        dummy.style.cssText = 'width:' + prop + '(1px);';
        if (dummy.style.length)
            return prop;
    }
})();

// Example of usage:
$('selector').css('height', calc + '(100% / 3)');

(Note: I omitted the -ms- prefix since IE now supports it without the prefix - refer to http://caniuse.com/calc.)

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

Guide: Utilizing JSON API data to generate marker labels on a leaflet map

Users are presented with points to click on. When a point is clicked, a menu displays text information. I have successfully placed the points, but when attempting to retrieve specific data from the database upon clicking a point, it does not show the marke ...

Unable to transform Symbol data into a string - Error when making a React AJAX delete call

I'm encountering an issue where I am getting a Cannot convert a Symbol value to a string error in the console. My tech stack includes React v15 and jQuery v3. https://i.stack.imgur.com/qMOQ8.png This is my React code snippet: var CommentList = Reac ...

I'm feeling pretty lost when it comes to understanding how line-height and margins work together

When creating a webpage layout, my goal is to maintain balance by ensuring there is an equal amount of spacing between sections and elements. However, when dealing with varying font sizes and line heights, achieving this can be challenging. To provide fur ...

Customize the appearance of the date input box in MUI KeyboardDatePicker

Currently, I am attempting to customize the appearance of the KeyboardDatePicker component including board color, size, font, and padding. However, none of the methods I have tried seem to be effective. Here is what I have attempted so far: 1 . Utilizing ...

This JavaScript operates in solitude, unable to collaborate with other JavaScripts

I received this code from an outsourced programmer: <script type="text/javascript"> $(function(){ $('#notif-icons > li > a, #top-menu > li > a').click(function() { var clicked = $(this).next('.popup-notif&a ...

Executing a function on the window object in JavaScript

I have come across the following code and am seeking guidance on how to get the last line to function correctly. The API I am using currently employs _view appended as its namespacing convention, but I would prefer to switch to something like arc.view.$f ...

Aligning a div within another div with an image

My current setup looks like this: HTML: <div class="wrapper"> <img src="image.jpg" /> <div class="circle"> X </div> </div> CSS: .circle { width:50px; height:50px; border-radius:50%; background: #FF0000; } ...

I'm having trouble accessing the outcome from within the function

Having trouble getting the result to return inside a function for my basic rock paper scissors game. I've tried everything, including console logging the compare and putting it inside a variable. Strange enough, console.log(compare) is returning und ...

Performing a simulated click on a dynamically inserted element using pure JavaScript

I am faced with the challenge of programmatically navigating a ReactJS-based website in a looped workflow. The process involves clicking on Element1, dynamically altering the web page to add Element2, then clicking on Element2, and so on until eventually r ...

Ways to showcase an item within additional items?

I'm struggling to properly display data in a table. My goal is to iterate through an object within another object inside an array and showcase the source, accountId, name, and sourceId in the table. https://i.sstatic.net/VVIuc.png <tbody clas ...

Tips on securely saving passwords using Greasemonkey

Created a custom userscript that prompts users to save their login credentials in order to avoid entering them repeatedly. Familiar with using localStorage.setItem() to store key-value pairs, but concerned about storing passwords in clear text. Seeking ad ...

Surprising block of text suddenly popped up on the browser screen while I was in the middle of working on

Currently delving into the world of MERN stack and working on a simple project. Everything was going smoothly on localhost until out of nowhere, some garbled text appeared on the screen, hindering my progress. I'm completely stumped as to what this my ...

Is there a way to convey a transition MUI property from a parent component to its child component in React?

My current setup involves a parent component with a button that triggers the opening of a snackBar from MUI (child component) upon click. To enhance the user experience, my teacher suggested adding a transition effect to the onClick event so that the snack ...

Tips for adjusting the height of MUI Date Picker to fit your preferences

<Box sx={{ m: 1 }}> <LocalizationProvider dateAdapter={AdapterDayjs}> <DatePicker label="Enter Date" slotProps={{ textField: { height: "10px" } }} ...

AngularJS Constants in TypeScript using CommonJS modules

Let's talk about a scenario where I need to select a filter object to build. The filters are stored in an array: app.constant("filters", () => <IFilterList>[ (value, label) => <IFilterObject>{ value: value, label: label } ]); i ...

When you use the useState object in NextJS, the context object may appear to be empty

I've encountered an issue while trying to pass a context object in NextJS that uses data from a useState hook. Strangely, the state variable and setState functions are undefined when consumed. It's puzzling because substituting a simple variable ...

React: Incorporating .map for nested arrays. Ensure each child component within the list is assigned a distinct "key" property

I have an array called navMenuItems that contains data for building a navigation menu with links and link names. Each item in the array may also contain child links, similar to the mobile menu on https://www.w3schools.com/. However, I'm encountering a ...

Trouble with Background Image Display in Internet Explorer 8

I have been attempting to set a background image for the . element, but it is not displaying correctly. The image shows up in Firefox and Chrome, but not in Internet Explorer. I have included a link to my website and relevant CSS code below. Can anyone pro ...

Issues with Angular preventing app from launching successfully

So I've been working on a Cordova app with AngularJS and everything seems to be running smoothly in Chrome and other browsers. However, when I try to install the apk on Android, AngularJS doesn't seem to execute the index.html upon launch. What& ...

Just a simple canvas animation

My canvas animation consists of two rectangles moving in different directions, but I believe it can be simplified further. http://jsfiddle.net/tmyie/R5wx8/6/ var canvas = document.getElementById('canvas'), c = canvas.getContext('2d&apo ...