Using <script> in CSS

Sangram Nandkhile picture Sangram Nandkhile · Jul 2, 2011 · Viewed 31.8k times · Source

Is there any way to write script in css and call or execute it whenever required ?

I need a <script> tag to be executed .

i need something like this..

css code

#execute{

<script> ..some script.. </script>

}

so whenever i use

<html>

.
.
.
.<div id="execute" />
.
.
.
.
</html>

so if i change the script changes will be reflected everywhere.

Is it possible?

EDIT:

Is it possible to keep my <script></script> tags inside some js file and i will host it. and then i will call some function() from my HTML so that the script will be executed everywhere i need it.

Can someone show me any example, tutorial how i can do it. I don't have much information about the Js file and how the function should be called.

Thank you all

Answer

redbmk picture redbmk · Jul 2, 2011

Does it have to be in CSS? jQuery is a great, simple way to do what you're asking. You put all your style information in the CSS (what it's intended for) and keep your javascript in the html or a .js file. Take a look at http://jquery.com. The code would look something like this

$(function() {
    $('#execute')
        .someCoolFunction()
        .anotherCoolFunction();
});

You use $(function() { /* code */ }); to run the code when your document is ready, and you use $('#execute') to grab the element with the execute tag. You can then do a lot of cool javascript really easily with that jQuery element.