Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integrate style tag using css

I try to add the <style type="text/css"></style> to head using jquery. I tried like this

 $("<style type='text/css'></style>").appendTo("head");

Previously, i have this type of

<style type="text/css">
img{ 
    -moz-animation:.6s rotateRight infinite linear; 
    -webkit-animation:.6s rotateRight infinite linear; 
}

@-moz-keyframes rotateRight{
    0%{ -moz-transform:rotate(0deg); -moz-transform-origin:50% 50%; }
    100%{ -moz-transform:rotate(360deg); }
}

@-webkit-keyframes rotateRight{
    0%{ -webkit-transform:rotate(0deg); -webkit-transform-origin:50% 50%; }
    100%{ -webkit-transform:rotate(360deg); }
}
</style>

That above style worked when I tried this with jquery like this:

$("<style type='text/css'>img{ 
    -moz-animation:.6s rotateRight infinite linear; 
    -webkit-animation:.6s rotateRight infinite linear; 
}

@-moz-keyframes rotateRight{
    0%{ -moz-transform:rotate(0deg); -moz-transform-origin:50% 50%; }
    100%{ -moz-transform:rotate(360deg); }
}

@-webkit-keyframes rotateRight{
    0%{ -webkit-transform:rotate(0deg); -webkit-transform-origin:50% 50%; }
    100%{ -webkit-transform:rotate(360deg); }
}</style>").appendTo("head");

but i get error in editor itself. Here is the pic enter image description here I think i messup something :( http://jsfiddle.net/jSvUE/

Any suggestion would be great Thanks, vicky

like image 812
Vignesh Pichamani Avatar asked Oct 18 '13 13:10

Vignesh Pichamani


1 Answers

Try

$("<style type='text/css'>img{ \
    -moz-animation:.6s rotateRight infinite linear; \
    -webkit-animation:.6s rotateRight infinite linear; \
} \
@-moz-keyframes rotateRight{ \
    0%{ -moz-transform:rotate(0deg); -moz-transform-origin:50% 50%; } \
    100%{ -moz-transform:rotate(360deg); } \
} \
@-webkit-keyframes rotateRight{ \
    0%{ -webkit-transform:rotate(0deg); -webkit-transform-origin:50% 50%; } \
    100%{ -webkit-transform:rotate(360deg); } \
}</style>").appendTo("head");

Working example: http://jsfiddle.net/jSvUE/2/

Really hackish, but for a quick-n-dirty solution, that'll work. The idea here is that you are escaping the new line. A more elegant way to accomplish this, though, is to put that img as a class, and use http://api.jquery.com/toggleClass/ to toggle the animation.

Update 2016

Here in 2016, ES6 is widely supported, and the above hack can be replaced with this still-horrendous blob:

$(`<style type="text/css">
img {
    animation: 600ms rotateRight infinite linear;
}
@keyframes rotateRight {
    0% { transform: rotate(0deg); transform-origin: 50% 50% }
    100% { transform: rotate(360deg) }
}
</style>`).appendTo("head");
like image 110
Scott Avatar answered Sep 21 '22 04:09

Scott