Elitmiar
Elitmiar

Reputation: 36829

Adding JavaScript at the bottom of a view using cakePHP

I have the following code

$this->addScript('<script type="text/javascript">
            $(document).ready(function() {
                alert("dsf");
            });
</script>');

Is it possible to add this at the bottom of my view? My reason being is it somehow always renders above the line where the jQuery library is included.

I've seen in the documentation they mention $scripts_for_layout, but I'm not sure how to use it.

Upvotes: 2

Views: 2555

Answers (3)

Anh Pham
Anh Pham

Reputation: 5481

Put the <script> tag for jQuery in the header (after the CSS).

Upvotes: 1

nIcO
nIcO

Reputation: 5001

If you want to place your JS code at a precise place in your view, you can use

$this->Html->scriptBlock('$(document).ready(function() {
            alert("dsf");
        }');

But if you do want to have your JS code in the header (but after the jQuery inclusion), you can just continue to use $this->addScript(), but make sure to place the variable $scripts_for_layout after the call to script():

echo $this->Html->script('jquery');
echo $scripts_for_layout;

Upvotes: 2

8vius
8vius

Reputation: 5836

You also not use CakePHP's helper for this, just put <script type="text/javascript"></script> at the bottom of your view after all your html

Upvotes: 1

Related Questions