WordPress use script only if class exist (or method)

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.

Read More

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….

Related posts

Leave a Reply

1 comment

  1. 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 😉