Majonsi
Majonsi

Reputation: 414

Change CSS properties of an element not in the DOM

I'm trying to add a css property to an element with the following command:

$(".pinned").css("left",colPositionLeft);

colPositionLeft is calculated when the page is loaded.

The problem is that the .pinned class is not present in the DOM when the page is loaded, pinned class is add to an element after the user had scroll. So, the command doesn't work.

How can I set the .pinned css property when the page is loaded but not present in the DOM?

Upvotes: 2

Views: 2847

Answers (2)

Lazzaro
Lazzaro

Reputation: 189

You can dynamically add CSS rules via JavaScript:

document.styleSheets[0].insertRule('.pinned { left: ' + colPositionLeft + 'px; }', 0);

adds the the rule as the first rule. To add it as the last rule you can use

var styleSheet = document.styleSheets[0];
styleSheet.insertRule('.pinned { left: ' + colPositionLeft + 'px; }', styleSheet.cssRules.length);

Both examples add the rule to the first style sheet (included file or <style> tag in the document) which should usually be sufficient. You can of course use other elements in document.styleSheets to add it to another.

Note that if you try to do this with a cross-origin style sheet it will throw a SecurityError in at least some browsers.

Upvotes: 5

andre mcgruder
andre mcgruder

Reputation: 1520

You can use the jQuery on function to modify out for dynamic element that may not have been loaded yet. I often use this function and find it very useful when creating templates and dynamic pages.

$(document).on('scroll', '.pinned', function(){
   $(this).css("left",colPositionLeft);
});

I used this add a reference. jQuery scroll

Upvotes: 0

Related Questions