Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I set multiple values of the same CSS property with Javascript?

Tags:

javascript

css

I want to programmatically set the CSS cursor value to both -webkit-grab and -moz-grab. For example, in a stylesheet, it would be represented as

mySelector{
    cursor:-webkit-grab;
    cursor:-moz-grab;
}

So here, the mySelector element has the cursor defined twice. Webkit browsers use the first definition, Firefox the second. I'm wondering if there is any way in Javascript to do the equivalent. I realize I could set a class, but my question was more for curiosity's sake to see if it was possible, than to solve a real-world problem I currently have.

Edit To clarify - the CSS I've posted (albeit with a valid selector) DOES work in both browsers. I'm just wondering if there's a javascript-only way to do this.

like image 620
Quasipickle Avatar asked Apr 11 '14 00:04

Quasipickle


2 Answers

You can also set the style using style.cssText property:

element.style.cssText = "cursor:-webkit-grab; cursor:-moz-grab; cursor:grab;";

Browsers will try to parse the value the same way they parse CSS and apply all the properties they can recognize. But I'd suggest to define these styles in a class and just add this class to the element instead.

like image 136
Ilya Streltsyn Avatar answered Oct 26 '22 21:10

Ilya Streltsyn


One way I have seen is to simply test whether the an assignment of the values was successful. If you assign a value the browser doesn't understand, it simply ignores it. For example in webkit:

> d = document.createElement('div')
  <div>​</div>​
> d.style.cursor = '-moz-grab';
  "-moz-grab"
> d.style.cursor
  ""

So you can use that behavior to roll your own function:

var setVendorStyle = (function() {
    var vendor_prefix = ['-moz-', '-webkit-'];
    return function(element, prop, value) {
        // try unmodified value first
        element.style[prop] = value;
        if (element.style[prop] === value) {
           return value;
        }
        // try vendor prefixes
        for (var i = 0, l = vendor_prefix.length; i < l; i++) {
           var vendor_value = vendor_prefix[i] + value;
           element.style[prop] = vendor_value;
           if (element.style[prop] === vendor_value) {
              return vendor_value;
           }
        }
        return false; // unsuccessful
    };
}());

Usage:

setVendorStyle(element, 'cursor', 'grab');

This probably won't work for every CSS property, especially not with shorthands, but hopefully for the ones with simple values.

like image 36
Felix Kling Avatar answered Oct 26 '22 19:10

Felix Kling