Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript beginner: add a dynamic style in javascript? [duplicate]

Tags:

javascript

css

Possible Duplicate:
How to create a <style> tag with Javascript

I write a dynamic form using java-script. I want to add the style in java-script itself. I write some code to add a style. But it is not working.This is the code am write in my project.

var sheet = document.createElement('style');
sheet.type="text/css";
sheet.innerHTML = "body{color:red;}";
document.body.appendChild(sheet);

Anyone help me please.

like image 765
yuva Avatar asked Oct 08 '22 03:10

yuva


2 Answers

Your code is fine.But i think that you are not calling it on right time, so call it when your body tag is loaded

 window.addEventListener('DOMContentLoaded',function(){
    var sheet = document.createElement('style'); 
    sheet.type="text/css"; 
    sheet.innerHTML = "body{color:red;}"; 
    document.body.appendChild(sheet);
    }, false);
like image 142
bugwheels94 Avatar answered Oct 18 '22 12:10

bugwheels94


HERE you can have some more resource to increase your knowledge. And I'm sure an example will be very useful! There are some SO questions that would help you too like THIS. --Credits Peter Boughton

This was tested in IE, FF and Opera:

var css = 'h1 { background: red; }',
    head = document.getElementsByTagName('head')[0],
    style = document.createElement('style');

style.type = 'text/css';
if(style.styleSheet){
    style.styleSheet.cssText = css;
}else{
    style.appendChild(document.createTextNode(css));
}
head.appendChild(style);

To add a class to an element:

document.getElementById("MyElement").className += " MyClass";

To remove a class from an element:

document.getElementById("MyElement").className = 
   document.getElementById("MyElement").className.replace
      ( /(?:^|\s)MyClass(?!\S)/ , '' )
/* code wrapped for readability - above is all one statement */

To do that in an onclick event:

<script type="text/javascript">
    function changeClass()
    {
        // code examples from above
    }
</script>
...
<button onclick="changeClass()">My Button</button>


Better yet, use a framework (in this example jQuery) which allows you to do the following:

$j('#MyElement').addClass('MyClass');

$j('#MyElement').removeClass('MyClass');

$j('#MyElement').toggleClass('MyClass');

And also:

<script type="text/javascript">
    function changeClass()
    {
        // code examples from above
    }

    $j(':button:contains(My Button)').click(changeClass);
</script>
...
<button>My Button</button>

This is separating HTML markup from your JS interaction logic, which is something that - especially on large/complex applications - can make maintenance significantly easier.

like image 36
waldyr.ar Avatar answered Oct 18 '22 11:10

waldyr.ar