views:

40

answers:

1

How do you pass items to the jQuery function "ready()" in Joomla?

$(document).ready(function(){
    // some code...
});

I'm already using this function and most items in it will be static (won't change based on modules, etc.). However, in some cases, I need to "inject" additional code into this function.

In particular, I have a custom JS function that sets an element's background image and it's called in this function, like this:

// Set background of element with ID and image path.
setBackgroundImage("img-2","global/img/rotator/ourstate.jpg");

This will be in a module. How do I pass that into the jQuery ready() function in Joomla? Thanks.

+2  A: 

There are no parameters for ready.

What you need to do is to set value for some hidden input element (with known ID) in your module. You module should generate the JS and add it to head element. In the JS code, get the value of the hidden field and do what you need to do.

For example:

--- MODULE (TEMPLATE)
....code before...

<!-- Un-submittable form --->
<form action="#" method="post" onsubmit="return false;">
     <input type="hidden" id="myBgImg" value="<?php echo 'image.jpg'; ?>" />
</form>


<?php
  $js = '
           $(document).ready(function() {
                //  Get Image
                var img = $("#myBgImg").value;
                if (img != ""){
                    // Set background of element with ID and image path.
                    setBackgroundImage("img-2","global/img/rotator/" + img);
                }
            });';

  JFactory::getDocument()->addScriptDeclaration($js);
?>

....code after...

I see you want to use rotator, so I assume you would like to load multiple image and change them over time.... You can set the myBgImg value to json encoded list [in php use json_encode() method] and decode it with JQuery http://api.jquery.com/jQuery.parseJSON/

Alex
is there any point in `<?php echo 'image.jpg'; ?>` ?
RobertPitt
*is there any point in <?php echo 'image.jpg'; ?>*Well it depends, if you want your value to be static then no, but if you want it to be configurable option (parameter driven) then YES--mod_mymodule.xml <param name="bgImage" type="list" default="nature.jpg" label="BG Image"> <option value="nature.jpg">Nature</option> <option value="animal.jpg">Animals</option> <option value="flower.jpg">Flowers</option> </param>--mod_mymodule.php <input type="hidden" id="myBgImg" value="<?php echo $params->get('bgImage', 'default.jpg'); ?>" />
Alex