How to include image, css and js file in codeigniter?

163 Views

How to include image, css and js file in codeigniter?

Codeigniter | Include image, css and js file

In codeigniter, we need to load URL helper in controller and then use base_url() function to load the resources.

// loading script
<script type='text/javascript' src="<?php echo base_url('js/jquery.min.js'); ?>"></script>

// loading image
<img src="<?php echo site_url('images/myimage.jpg'); ?>" />
 

Codeigniter uses absolute path to load the resources. Also there is an inbuild helper class which is use to load the resources in view.
so for this let's create a assets folder in our root directory. Again create a css, js and image folder inside assets folder and placed css file in css folder, js file in js folder and image file in image folder. 

For now let's say we have "style.css" file in css folder, "img.jpg" in image folder and "demo.js" in js folder.

The directory structure seems like bellow:

 // root folder
 codeigniter|
            |____application
            |____assets|
            |          |___css|
            |          |      |___style.css
            |          |
            |          |___images|
            |          |         |___img.jpg
            |          |___js|
            |                |___demo.js
            |____system
            |___......
            |.........

Now create a "Demo.php" file with bellow code and save it inside application/controllers folder. 

 <?php 

   class Demo extends CI_Controller {
	
      public function index() { 
         $this->load->helper('url'); 
         $this->load->view('demo'); 
      } 

   }
 
?>

 

 

Create a view file called demo.php and pest the bellow code and save it inside application/views folder.

 <!DOCTYPE html> 
<html lang = "en">
 
   <head> 
      <meta charset = "utf-8"> 
      <title>Codeigniter | Include image, css and js file</title> 
      <link rel = "stylesheet" type = "text/css" href = "<?php echo base_url('assets/css/style.css'); ?>"> 
      <script type = 'text/javascript' src = "<?php echo base_url('assets/js/demo.js'); ?>"></script> 
   </head>
	
   <body> 
      <img src="<?php echo base_url('assets/images/img.jpg') ?>">
      <a href = 'javascript:test()'>Click Here</a> to execute the javascript function. 
      
   </body>
	
</html>

 

Code for "style.css" file

 body { 
    background: #000;
    color: #FFF;
    font-size: 24px;
    text-align: center; 
}

 

Code for "demo.js" file

 function test() { 
   alert('This page contain one image'); 
}

 

Now use the following URL in the browser to execute the above example.

http://yoursite.com/index.php/demo

or

http://localhost/codeigniter/index.php/demo

 

Tags:-
Codeigniter