views:

442

answers:

2

Hello,

I have an app where I need to call some JS in the onLoad event of the BODY tag of two forms. However, I can't find how to modify the tag for just them. Does anyone know?

Frank

+4  A: 

You don't need to modify the body tag to have Javascript execute when the page loads. You could just include something like this in your layout where appropriate:

(jQuery)

$("body").load(
    function(){
        // do stuff when the body element is loaded.
    }
);

Or, if you want to have the code execute when the document.ready event fires:

$(function(){
        // do stuff when the document is ready
    }
);

Or, if you don't want to use jQuery, you could do something like this:

function doStuff(){
    // whatever you want to happen when the load completes
}

window.onload = dostuff;

Good luck - and please clarify your question if this answer isn't satisfactory.

inkedmn
+3  A: 

inkedmn certainly has provided the right answer for this case, but in general, you can "hand information up" like this:

(in views/controller/view.ctp)

$this->set('bodyAttr', 'onload="something"');

(in views/layouts/default.ctp)

<?php
    if (isset($bodyAttr)) {
        $bodyAttr = " $bodyAttr";
    } else {
        $bodyAttr = null;
    }
?>
<body<?php echo $bodyAttr; ?>>

I often use it like this to add extra classes to a "top level element":

<?php
    if (!isset($docClass)) {
        $docClass = null;
    }
?>
<div id="doc" class="<?php echo $docClass; ?>">
deceze
I do prefer setting values in the controller.
Wayne Khan
For something like classes I don't, as they're purely view-layer related.
deceze