I have this jQuery Plugin that looks like this:
(function($){
$.fn.s3Slider = function(vars) {
// (...)
timeOutFn = setTimeout(makeSlider, thisTimeOut);
// (...)
var makeSlider = function() {
// next Image
}
makeSlider();
};
})(jQuery);
I can start it with
jQuery(document).ready(function() {
jQuery('#s3slider').s3Slider({
timeOut: 4000
});
});
Now my question, how can I execute the makeSlider() function from outside? It's an Image Slider and I want to add a Next Button function.
I want something like this, but it's wrong
jQuery.s3Slider.makeSlider();
-
@Neal sorry didnt realize he wanted it OUTSIDE of the functionMath chiller– Math chiller2013年08月26日 19:13:29 +00:00Commented Aug 26, 2013 at 19:13
4 Answers 4
You can return an object containing references to the functions you want to expose:
(function($){
$.fn.s3Slider = function(vars) {
...
function next(){
// Advance the slide here
}
// Return only the functions that you want to expose
return {
next: next
};
}
};
})(jQuery);
Then you can use it like:
var s3Slider = jQuery('#s3slider').s3Slider({
timeOut: 4000
});
s3Slider.next();
1 Comment
$.fn.s3Slider = function(...) {
...
return { makeSlider: makeSlider };
}
Comments
Currently makeSlider only exists inside the scope of the s3Slider function.
Why not make makeSlider it's own plugin, then have s3Slider (and you) call that?
(function($){
$.fn.makeSlider = function(){
// Next image
};
$.fn.s3Slider = function(vars){
// Your code
var that = this;
setTimeout(function(){
$(that).makeSlider();
}, thisTimeOut);
};
})(jQuery);
Comments
You can achieve what you want but it's a little more complex.
Change
$.fn.s3Slider = function(vars) {
// (...)
timeOutFn = setTimeout(makeSlider, thisTimeOut);
// (...)
var makeSlider = function() {
// next Image
}
makeSlider();
};
to
$.fn.s3Slider = (function(){
var makeSlider;
var f = function(vars) {
// (...)
timeOutFn = setTimeout(makeSlider, thisTimeOut);
// (...)
makeSlider = function() {
// next Image
}
makeSlider();
};
f.makeSlider = makeSlider;
return f;
})();
After that, you can both use the s3Slider function as
$(someElement).s3Slider()
and do
$.fn.s3Slider.makeSlider();
or
$(someElement).s3Slider.makeSlider();
to access makeSlider from outside.
1 Comment
s3Slider is a property of $.fn (which is a alias to jQuery.prototype). jQuery.s3Slider is not defined in your answer. You'd have to do $(someElement).s3Slider().makeSlider() (or $.fn.s3Slider.makeSlider();).