5

A client has changed their CSP to ban inline styles on their server. As far as I can tell, this means that we can no longer use JS to dynamically position/animate/style HTML elements e.g. we can't detect the position of a DOM element and position another element next to it via JS.

Is this correct? Is there a workaround for us to dynamically animate DOM elements with this CSP restriction in place?

Wyzard
  • 33,849
  • 3
  • 67
  • 87
  • 1
    you dont need javascript for animations, you can set animated classes using css3 keyframes and transitions, and simply attach the classes to relevant elements. the sad part however, that the attaching will have to be performed using javascript anyway. there is no way to animate dom elements without using javascript, without refreshing the whole page... – Banana Jul 12 '14 at 14:01
  • 1
    Thanks, but I do need to be able to dynamically position elements with JavaScript by setting the CSS position. For instance. I will need to look up the position of an element (left) and then change this position via JavaScript. So I will need to set an line style like style="left:343px;. I won't know what this position is until the page loads. The only thing I can think of is to create a a whole load of classes which cover all of these positions, (e.g. left1: left:1px;) Is there another way? – James Carpenter Jul 12 '14 at 14:08
  • no man don't do that, it might double your traffic if not triple it. have a look [Here](http://stackoverflow.com/questions/1720320/how-to-dynamically-create-css-class-in-javascript-and-apply), it might give you a direction: – Banana Jul 12 '14 at 14:13

2 Answers2

22

The proper workaround for this issue is to use the CSS Object Model (CSSOM).

Given the following ways of setting the style:

  1. <p style="left: 343px">...</p> // fails due to CSP
  2. document.getElementById(id).setAttribute('style', 'left: 343px'); // fails due to CSP
  3. document.getElementById(id).style.left = '343px';

Only the last one will successfully comply with a CSP directive of style-src: self (because it's using the CSSOM).

That's why using jQuery's .css() function works:

When using .css() as a setter, jQuery modifies the element's style property. For example, $( "#mydiv" ).css( "color", "green" ) is equivalent to document.getElementById( "mydiv" ).style.color = "green".

Mike Post
  • 6,355
  • 3
  • 38
  • 48
  • One can also use `document.getElementById(id).style.cssText = 'left: 343px'` to have a very similar to `setAttribute` API – Finesse Jan 28 '22 at 16:24
-7

JavaScript is executed on the client. Unless the filtering software is incredibly clever, you can still add dynamic inline styles as the server has no idea what's happening in the browser. What you can't do, however, is add inline styles as part of the HTML you send to the client.

Bojangles
  • 99,427
  • 50
  • 170
  • 208