2

I`m making some functions with Jquery. but I got problem.

function fader(elm,delaytime) {
 elm.each(function(index){
 $(this).css('visibility','visible').delay(delaytime*index);
 $(this).fadeIn(1500);
 });
}
fader($('.subImgs').children(),200);

It was good, and I wanted more.

$.fn.fader2 = function(elm,delaytime) {
 elm.each(function(index){
 $(this).css('visibility','visible').delay(delaytime*index);
 $(this).fadeIn(1500);
 });
}
$('.subImgs').children().fader2(200);

It doesn't work. I know something was different but I couldn't find it. anyone can help me?

Felix Kling
820k181 gold badges1.1k silver badges1.2k bronze badges
asked Mar 19, 2012 at 15:41
1
  • 3
    Have a look at docs.jquery.com/Plugins/Authoring to learn the basics of jQuery plugin development. Your code does not work because elm has the value 200. It does not refer to the selected elements. Commented Mar 19, 2012 at 15:43

2 Answers 2

2

Your function should probably read:

$.fn.fader2 = function(delaytime) {
 return this.each(function(index){
 $(this).css('visibility','visible').delay(delaytime*index).fadeIn(1500);
 });
}

Working fiddle (slighty different code for better visibility): http://jsfiddle.net/2HMWF/

See the link from the comment above for great information on that topic: http://docs.jquery.com/Plugins/Authoring

answered Mar 19, 2012 at 15:53
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your help. short and perfect! and thanks for your comment. The doc really helps me.
1

You might also try:

(function($) {
 if (!$.myFader) {
 $.extend({
 myFader: function(elm, delaytime) {
 return elm.each(function(index){
 $(this).css('visibility','visible').delay(delaytime*index).fadeIn(1500);
 });
 }
 });
 $.fn.extend({
 myFader: function(delaytime) {
 return $.myFader($(this), delaytime);
 }
 });
 }
})(jQuery);

This should allow both

$.myFader($('.subImgs').children(),200);

and

$('.subImgs').children().myFader(200);
answered Mar 19, 2012 at 17:01

3 Comments

I didn't know such this method is. Thank you very much.
No prob, that is some insight on how to begin a jquery plugin, for more, check out there docs
You don't necessarily need .extend(). In fact, .extend() is slower that just saying $.fn.method = function() {}. Also, $.fn.myFader doesn't need $(this); it only needs this, because this refers to the jQuery object.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.