0

I want to be able to dynamically change width and height in a div that gets created by a function. The code below works but the style rules gets added directly in the HTML document, which is something I want to avoid. Instead I want the properties to be added directly to the CSS file. Is there a way to achive that?

...function(width, height) {

var div = $('<div/>', {
    class':  'window',
    width': width,
    height': height
}).appendTo('#content');

}

2 Answers 2

4

You can't write directly to the CSS files using jQuery or JavaScript, you can append in the live / rendered HTML (like you're doing above).

Why not add a class to the CSS and just switch or append that class to your DIV using jQuery?

Sign up to request clarification or add additional context in comments.

Comments

1

why do you need to add a class in CSS file with jquery? You can't do this directly. You can add a <style>....</style> tag in your HTML page's <head> tag with jQuery which is support you much. You can use the following methods to solve this:

var myStyle = { "width": "100%", "height": "90%" };
$('#content').css(myStyle);

OR

$("<style type='text/css'>#content { width: 100%; height: 90% }</style>").appendTo("head");

OR

 $.rule('#content{  width: 100%; height: 90% }').appendTo('style');

But remember you need to use plugin for use $.rule .

2 Comments

Yes, this should work but the thing is that I want my HTML page to be clean from CSS, ie. even in the head.
@Arif you should mention in your answer that $.rule is not supported by the jquery core, you have to include a plugin

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.