Search code examples
javascriptcssvendor-prefix

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


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';

Solution

  • 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';