Reputation: 19735
If I have this line in my view:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
Do I also put my actual script in my view?
<script type="text/javascript">
$(document).ready(function() {
alert("Hello world!");
}); </script>
Or do I put my actual javascript somewhere else and send it to the view somehow?
Thanks.
Upvotes: 3
Views: 2475
Reputation: 131
When developing a codeigniter application, I usually use a template which loads three views:
In the Scripts View, I load the common JavaScript libraries that are required by every page (e.g. jQuery etc). For page specific JavaScript, there are two options that you could follow:
In the end, it really comes down to what you are really comfortable with and the efficiency.
Upvotes: 2
Reputation: 1315
I have all of my js in a folder and call it when i need them.
This is more orderly in my opinion, but theres no rule stating you can't have javascript in your views. if its something simple that wont get re-used, then go ahead and keep it in the view.
Upvotes: 0
Reputation: 25776
This is how i do it. For page specific javascript i include it in the page itself. For other javascript that would need to be run on most pages i put it in the global javascript, mine is called main.js.
So, as an example, say you would like to hide some_div on page load, and this div is on a specific page.
<body>
<div id="content">
<div id="some_div">
</div>
</div>
</body>
Then you would just do that in the page specific javascript.
An example of the main/global javscript file would be js that you want run on each page. So some examples are fadeIn animations for the content area, if all/most your pages have a content area and you would like to fade the content in on every page load, then the global java script would be a good place to put it so you don't have repeated code. Another example is if you want to make all inputs with a class="calendar"
into a datepicker, then in your global js file you would just do.
$(function(){
$('.calendar').datepicker()
});
This way you don't have to do that for each page and have repeated code. Long story short, if you are going to use the same js code in other pages too then might as well put it in a global js file.
In relation to codeigniter. What i did was create a "view partial" (really just a view) for all my js and css files. So in my view js.php
i have:
<script type="text/javascript" src="/javascript/jquery.js" /> </script>
<script type="text/javascript" src="/javascript/jquery-ui.js" /> </script>
<script type="text/javascript" src="/javascript/main.js" /> </script>
Then i just reference this view partial in the view page that i need to include the scripts i.e
<?php $this->load->view('/common/js') ?>
This way i don't need to manually include the javascript files i need for each view.
Upvotes: 5