Updating CSS using simple JavaScript ... how can I update if a property uses vendor prefixes?

For example, if I want to capture an 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 using JavaScript, but I can still cover all three, how do I do this? I just assign them in three lines - is JavaScript rolling back to its previous destination?

 document.getElementById('theDiv').style.cursor = '-webkit-grabbing'; document.getElementById('theDiv').style.cursor = '-moz-grabbing'; document.getElementById('theDiv').style.cursor = 'grabbing'; 
+7
javascript css vendor-prefix
source share
3 answers

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

2) If you try your way, Javascript will reassign this property 3 times and in the end will be the last one executed as active, 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 will do this. eg:

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

and

  js:- document.getElementById('theDiv').className += 'myClass'; 
+11
source share

No, Javascript reassigns the property 3 times and ends with the last one executed as active.

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

At the end of the day, your JS runs on a specific user’s machine with a specific browser, therefore, finding a browser and applying the appropriate style for that browser will 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'; } 
+2
source share

It is probably useful to know in this regard: if you try to set an invalid value, the browser ignores 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
source share

All Articles