Updating CSS via plain JavaScript... how do I update if the property uses vendor prefixes?

334 views Asked by At

For example, if I want a grabbing icon for my cursor, in CSS I would use this:

div {
     cursor: -moz-grabbing;
     cursor: -webkit-grabbing;
     cursor: grabbing;
    }

But let's say, I want to implement this via JavaScript but still being able to cover all three, how do I do this? Do I just assign them in three lines -- does JavaScript fallback to the previous assignment?

document.getElementById('theDiv').style.cursor = '-webkit-grabbing';
document.getElementById('theDiv').style.cursor = '-moz-grabbing';
document.getElementById('theDiv').style.cursor = 'grabbing';
3

There are 3 answers

1
Naeem Shaikh On BEST ANSWER

1) You can add a class for that purpose which assigns all the properties.

2) If you try it your way then, Javascript will reassign the property 3 times and end up with the last one executed as the active one, So

    document.getElementById('theDiv').style.cursor = '-webkit-grabbing';
    document.getElementById('theDiv').style.cursor = '-moz-grabbing';
    document.getElementById('theDiv').style.cursor = 'grabbing';

will not work.

3) Adding a class would do it. for example:

    css:-
    .myClass {
      cursor: -moz-grabbing; 
      cursor: -webkit-grabbing; 
      cursor: grabbing; 
     }

and

   js:-

   document.getElementById('theDiv').className += 'myClass';
0
Felix Kling On

Probably good to know in this regard: If you are trying to set an invalid value, the browser will ignore it. So something like this works:

function setStyle(element, property, value) {
    var prefix = ['', '-webkit-', '-moz-'];
    var i = 0;
    var style = element.style;
    do {
        style[property] = prefix[i] + value;
        i += 1;
    }
    while(style[property] !== prefix[i] + value && i < prefix.length);
}
1
Alexus On

No, Javascript will reassign the property 3 times and end up with the last one executed as the active one.

What you want is to detect which browser you are using with javascript and then apply the appropriate one.

In the end of the day your JS is executed on the user's specific machine with the specific browser so by detecting the browser and applying the appropriate style for that browser you solve your problem.

Pesudo Code:

if(isMozilla) {
    document.getElementById('theDiv').style.cursor = '-moz-grabbing';
}
else if(isChrome OR isSafari) {
    document.getElementById('theDiv').style.cursor = '-webkit-grabbing';
}
else {
    document.getElementById('theDiv').style.cursor = 'grabbing';
}