Put dataTables on every page across site

Put dataTables on every page across site

NinjaPenguinSLCNinjaPenguinSLC Posts: 3Questions: 2Answers: 1
edited September 2015 in Free community support

I've gotten DataTables to work on a single page, but I'm wondering if there's a clean way to abstract it out so that I can add a single line of code to each page in order to implement DataTables. Most of my work is in .php files, and when I add the below code, everything on that one page works swimmingly. So I guess what I'm asking is if there's a way to basically move this code to one, completely separate page, and then import it as a script? Or at least stick the <link...> and <script...> files in their own page?

The code:

<link rel="stylesheet" type="text/css" href="DataTables-1.10.9/media/css/jquery.dataTables.css">
<!-- jQuery -->
<script type="text/javascript" charset="utf8" src="DataTables-1.10.9/media/js/jquery.js"></script>
<!-- DataTables -->
<script type="text/javascript" charset="utf8" src="DataTables-1.10.9/media/js/jquery.dataTables.js"></script>

<script>
$(document).ready(function() {
        $('table.display').DataTable({
            "scrollY":          "400px",
            "scrollCollape":    true,
            "paging":           false,
            "sDom":             '<"toolbar"f><"top">rti<"bottom"lp><"clear">'
        });
});
</script>

This question has an accepted answers - jump to answer

Answers

  • NinjaPenguinSLCNinjaPenguinSLC Posts: 3Questions: 2Answers: 1
    Answer ✓

    I ended up figuring it out! I was able to create a file, dataTables.js with this code:

    jQuery(document).ready(function($) {
        loadCSS = function() {
            var cssLink = $("<link rel='stylesheet' type='text/css' href='DataTables-1.10.9/media/css/jquery.dataTables.css'>");
            $("head").append(cssLink);
        };
    
        loadJS = function() {
            var jsLink =$("<script type='text/javascript' charset='utf8' src='DataTables-1.10.9/media/js/jquery.js'></script>");
            var jsLink2=$("<script type='text/javascript' charset='utf8' src='DataTables-1.10.9/media/js/jquery.dataTables.js'></script>");
            $("head").append(jsLink);
            $("head").append(jsLink2);
        };
        loadCSS();
        loadJS();
    });
    
    $(document).ready(function() {
            $('table.display').DataTable({
                "scrollY":          "400px",
                "scrollCollape":    true,
                "paging":           false,
                "sDom":             '<"toolbar"f><"top">rti<"bottom"lp><"clear">'
            });
    });
    

    and then adding this code into the same file that I call import jQuery and have on every page of my site:

        <script type="text/javascript" src="dataTables.js"></script>
    

    and now every page I have a table on uses DataTables.

This discussion has been closed.