Kamil Sucharski Kamil Sucharski - 3 months ago 9
HTML Question

Passing an animation function as a parameter

I am trying to pass a fadeIn/fadeOut/etc function as a parameter to a larger function, but it's not working. This is how I initiate it:

$("#buttFadeOut").click(function() {
$('#lista').fade( function () {
fadeOut(500);
}, 150);
});


And this is where it goes:

$.fn.fade = function(passedFunction, pauseDuration){
var elem = this.children().first();
var len = elem.siblings().length;
for (var i=0;i<=len;i++) {
var fun = passedFunction();
elem.delay(pauseDuration*i).passedFunction();
}
elem = elem.next();
}


I get the error saying that elem.delay(...).passedFunction is not a function, but if I check it with $.isFunction(passedFunction) it returns true. With normal functions it's working but (if I'm assuming correctly) since I'm running it on 'elem' it refuses to work. Any fixes for that?

Answer

elem.delay(pauseDuration*i).passedFunction(); tries to call a jQuery plugin called passedFunction() which is not there.

One solution could be to pass a callback function like below, you might also have to move elem = elem.next(); inside the for loop

$("#buttFadeOut").click(function() {
  $('#lista').fade(function(el) {
    $(el).fadeOut(500);
  }, 250);
});


$.fn.fade = function(passedFunction, pauseDuration) {
  var elem = this.children().first();
  var len = elem.siblings().length;
  for (var i = 0; i <= len; i++) {
    elem.delay(pauseDuration * i).promise().done(function() {
      passedFunction(this);
    });
    elem = elem.next();
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="buttFadeOut">Test</button>
<ul id="lista">
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
</ul>

Comments