Hi all, I am building a common function library but the functions inside need to reference different jquery files, which they may need to be referenced in some pages but not in others.

When I called this common function library in one web page which is only going to use one function, and I don't reference the files need it for the other function, then it will create a script error.

My question is if it would be possible to stop this script errors like...

//This if statement is what I was thinking to stop going through
    if ($(".objectdate") != null){
//This is the function that is calling other jquery files and creates error.
        $(document).ready(function() {
            $(".objectdate").datepicker({
        //Code inside.
        });
        }); 
    }

1 answer

Mottie 1134
0
points
This was chosen as the best answer

I believe the problem is having the $(document).ready(function(){.... } inside of the if statement.. Don't quote me on this, but I think jQuery looks for all the ready functions and executes the code inside when the document is ready. So try moving the ready function to around your code instead of inside. Also, use $(".objectdate").length instead of checking to see if it is not null.

$(document).ready(function() {
   if ($(".objectdate").length){
    $(".objectdate").datepicker({
      //Code inside.
     });
   };
})

Also, it might be better to look to see if the function exists instead of the page element.

if (typeof(datepicker)!="undefined"){ 
 $(".objectdate").datepicker({
   //Code inside.
  });
}
Answered over 6 years ago by Mottie