Reputation: 492
I want to run a bit of JS once the body has loaded. My framework loads the header/footer from two different files that are static and the body is dynamic. Therefore reading online I could place the $(elem).load(function()) at the end of body and as the page loads it would run the function? I tried this briefly but it doesn't seem to work.
{%include file='/var/www/include/tpl/header.tpl'%}
<div id="contentMain">
<h1>{%$heading%}</h1>
{%if isset($Details)%}
<h4>Details</h4>
{%$Details%}
{%/if%}
{%$table%}
</div>
<div id="space">
</div>
<script>
$("#contentMain").load(function(){
alert("It worked!");
//run some stuff here
});
</script>
{%include file='/var/www/include/tpl/footer.tpl'%}
Any help as to how to get this to work would be much appreciated!
Upvotes: 0
Views: 116
Reputation: 1938
You can do this using jquery's document.ready.
On the header, Include jquery reference.
<script type="text/javascript">
$(document).ready(function() {
alert("It worked!");
});
</script>
</head>
Upvotes: 0
Reputation: 95020
In your case you do not need to wait due to the location of your script. The script wont be parsed/executed till the elements above it are parsed. Therefore, it's safe to assume the contentMain div and it's descendants are ready to be manipulated.
{%include file='/var/www/include/tpl/header.tpl'%}
<div id="contentMain">
<h1>{%$heading%}</h1>
{%if isset($Details)%}
<h4>Details</h4>
{%$Details%}
{%/if%}
{%$table%}
</div>
<div id="space">
</div>
<script>
alert("It worked!");
//run some stuff here
</script>
{%include file='/var/www/include/tpl/footer.tpl'%}
Upvotes: 0
Reputation: 4449
jQuery has a handy-dandy little function that you can attach to the document to run functions once the body has loaded. It is the ready function.
$(document).ready(function() {
//Place code here to do stuff
});
Doing it this way, you can ensure that the body and all of its content has loaded before any of the stuff inside of the function runs.
Upvotes: 3