0

In wordpress, to use $ instead of jQuery prefix, i added the following code around all js code:

jQuery(function($) {
    ...
});

It works well, but i cannot call an object from another javascript file, the following problem persists:

Slider is not defined

This is my code:

file1.js

jQuery(function($) {
    var slider = new Slider();
});    

file2.js

jQuery(function($) {
    function Slider() {
       this.nb_ele = 10;
    }
});

It seems that because the workspace of two js files is different so they can't call function from another one. Any solution?

2 Answers 2

4

The issue you have is that Slider is not accessible outside of its scope as that's defined by the .ready() though you've used shorthand for that. The function needs to be available in the global scope:

file1.js

function Slider() {
   this.nb_ele = 10;
}

jQuery(function($) {
  // ...
});

file2.js

jQuery(function($) {
    var slider = new Slider();
}); 

If you want Slider to stay in the document ready, you'll need to use a function expression to add the function to the global object:

jQuery(function($) {
    window.Slider= function () {
       this.nb_ele = 10;
    };
});

See Also: https://stackoverflow.com/questions/1449435/splitting-up-jquery-functions-across-files

1
  • That's what i need, thank you. I need to use the jQuery in Slider function so it must stay in the jQuery scope but by adding "window" before the function name, it'll be added to the global object. Commented Mar 28, 2016 at 23:44
2

I had the same kind of problem.

You can also solve it with:

var $ = jQuery.noConflict();
$(document).ready(function(){

your code in here

});

You need also to use that trick in all of your javascript files, i mean var $ = jQuery.noConflict();.

After that Dammeul is right.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.