Adding JS and CSS in CodeIgniter
×

Adding JS and CSS in CodeIgniter

1806

  • From the point of view of code customization, it is very necessary to use external CSS and JS files rather than writing all codes into one file.
  • In Codeigniter, it is very simple to add external CSS and JS files to your page.

  • Related Topics:

    Codeigniter Interview Questions
    Page caching in Codeigniter
    Page redirecting in Codeigniter

    Adding CSS and JS in CodeIgniter

  • Create CSS and js folder in the root directory of your project which contains all CSS and JS files respectively.
  • To include CSS and JS files into your view file, use HTML tags <link> and <script> respectively.
  • <link rel = "stylesheet" type = "text/css"
    href = "<?php echo base_url(); ?>css/style.css">

    <script type = 'text/javascript' src = "<?php echo base_url();
    ?>js/script.js"></script>
  • To use the base_url() function, you have to load the URL helper into your controller file.
$this->load->helper('url');

Example:

Step 1 Open the CSS folder and create a CSS file style.css.

body {
background:#FFF;
}
h2{
color:red;
}
h4{
color:blue;
}

Step 2 Open the js folder and create a JS file script.js.

function example() {
alert('Hello, This is example function');
}

Step 3 Open the application/views directory and create a new file example.php.

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">

  <title>Codeigniter Example</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<link rel = "stylesheet" type = "text/css" href = "<?php echo base_url(); ?>css/style.css">
<script type = 'text/javascript' src = "<?php echo base_url(); ?>js/script.js"></script>
</head>
<body>

<div class="container">
<h2>Codeigniter Example</h2>
<h4> <a href = 'javascript:example()'>Click Here</a> to execute the javascript function.</h4>
</div>

</body>
</html>

Step 4 Open the application/controllers file and create a new file Example_controller.php.

<?php
class Example_controller extends CI_Controller {

public function index() {
$this->load->helper('url'); //load this url to use base_url() function
$this->load->view('eexample');
}
}
?>

Step 5 Enter the given URL into the browser to see the result.

http://localhost/ci/index.php/Example_controller

Click on the click here link to execute the JS function.



Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments