Search code examples
phpjavascriptjqueryuniversal

Placing javascript/jquery functions in a universally accessible page


I am trying to clean up my pages, and one of the major ways that I am doing so is to put JavaScript and JQuery functions into a file called 'scripts.js' that is automatically accessed upon page load.

I've run into a problem with functions that use php to call from the page itself. For example, the following function doesn't work, and in fact 'kills' the script for all pages (so now things that were supposed to be hidden are not, and things are not loading properly). I've narrowed it down to the fact that I use to call a variable. I would really like to be able to keep functions using PHP in this universal file as opposed to clogging up the HTML template pages, any thoughts on either how to make this work, or if not how else I may be able to call the values needed? They are always extracted to the page before rendering if that helps.

function positiveSelect()
{
   var size = <?php echo $idea[0]["size"]; ?> * 1;
   if (size > 5)
      return true;
   else
      return false; 
}

Solution

  • if you can't retrive your data form the DOM itself you can store values with the corresponding object:

     <div data-size=20>
    

    and then retrive it with:

     $(element).data("size");
    

    or if you have global data you want to store you can create a value "container" in the head of you html document like this:

    <script type="text/x-json" class="global-data">{"value1":"1","value2":"2"}</script>
    

    and then read the content of that element and parse it with JSON.parse