tags:

views:

45

answers:

3

EDITED:

Just wondering if is it possible to add a function (or static script) block or a variable to body of html.

Something like this,

$('body').add(function(){/../}) 

or

$('body').append('<script></script>')

or

$('body').fn.myFunc = function(){}

Is it correct to use .extend instead?

One example is if I use ExternalInterface, my callbacks have to be statically defined in body/html/js but not in $().ready function unless I have a var defined globally and refer it in $().ready function.

I overlooked this requirement, and thats where I wanted to add dynamic callback functions.

A: 

There is a method $.getScript(), you can use that too.

Example:

<script>$.getScript("http://dev.jquery.com/view/trunk/plugins/color/jquery.color.js", function(){
  $("#go").click(function(){
    $(".block").animate( { backgroundColor: 'pink' }, 1000)
      .animate( { backgroundColor: 'blue' }, 1000);
  });
});</script>
Sarfraz
+1  A: 
  • To create a script tag in your markup

    $('<script/>', {
        type:    'text/javascript',
        src:     'http://...'
    }).appendTo(document.body);
    
  • To extend jQuery use

    $.fn.yourmethodname = function(){
    });
    
jAndy
A: 

You can pretty much attach a function to almost anything in Javascript, it really doesn't care.

In your last option, the fn object has to exist on the body DOM object before you can attach more functions to it.

Something like this would work:

$(function() {
    $('body')[0].fn = function() {};
    $('body')[0].fn.myFunc = function() { alert('Yay function'); };
});

Or, if you just want the functions right on the body element:

$('body')[0].myFunc = function() { alert('Yay function'); };

Make sure you include the [0] bit on the end of $('body'), or you will be attaching your function to a JQuery object that wraps the body DOM object. I don't think you can be assured that every time you call $('body') you will get the exact same JQuery object.

ntcolonel
Couldnt define function thisway. fn is undefined.
prem
I know fn isn't defined, that's what this is for:$('body')[0].fn = function() {};
ntcolonel