2
votes

i have a problem with script in wordpress. I have included script in functions.php in theme folder

function my_scripts_method() {
   wp_register_script( 'my-js-file',
       get_template_directory_uri() . '/js/my-js.js',
       array( 'jquery' ),
       '1.0',
       false );

   wp_enqueue_script( 'my-js-file' );
}

add_action( 'wp_enqueue_scripts', 'my_scripts_method' );

and my script with some adjustments in my datepicker ui. But that script is included all the time and when the form with datepicker in not on the page, it doesn't knows "datepicker" and its methods. Web is than without the background and with other problems.

I figured out, that i can check, if the class of forms date field exists or the whole plugin (its visual form builder) is on that page, but it doesn't work. Wordpress is processing that script even if the class is not on current page.

i tried many things like

if ($(".visual-form-builder-container")){  

but it still loads that script on the main page, where this element doesn't exists. Please help

this is that script:

if($(".visual-form-builder-container").length > 0) { <-- Im trying to stop that here

    jQuery(document).ready(function($) {
        $.datepicker.setDefaults({
                    firstDay: 1,
                    minDate: 0,
        });    
    });

}

EDIT: Maybe i found something. When i open my website without any "if" in my scrip and check the chrome console, there is: Uncaught TypeError: Cannot call method 'setDefaults' of undefined So if i maybe need something like: if is method defined and than it should work but i do not know any function, that checks methods....

1
try if($("yourselector").length > 0) {} ?? - Mike C.
still doing the same. I don't have a problem with checking the class - that works, but when that class exists on one page of the webside it uses that scritp everywhere - Kulikjak
yes, but your my_scripts_method() is what actually is registering the script, and that is what you want to stop, right? - Mike C.
What is the URL of the page you would like to add it to? Perhaps it's best to ask via Wordpress to enqueue it only if it's on X page based on the criteria you need it to show. So if(is_page('criteria') then you add the enqueue to it. - Marco Berrocal
well that is solution too but im not sure that the best one. I will continue adding pages and dont wanna change it. - Kulikjak

1 Answers

0
votes

Ok a probably solved it. I just added try and catch to the script (here is my code):

jQuery(document).ready(function($) {
   try{
     $.datepicker.setDefaults({
            firstDay: 1,
            minDate: 0,
     });     
     $( '#vfb-datum-75' ).datepicker({
            beforeShowDay:  ..........,
     }); 
   }catch(err){

   }    
});

So now it works, when everything is ok and when something is undefined, it will do nothing and thats good Anyway thanks for your help ;)