Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: if inside a chain?

I have this

if(noDelay){
  $(element).find("." + options.class).remove();
} else {
  $(element).find("." + options.class).fadeOut().remove();
}

Is there a way I could avoid repeating the sentence and only add the fadeOut() when a given condition is met?

I can't move fadeOut() till the end of the chain, which probably would've made things easier.

I'm thinking something like

$(element).find("." + options.class).(if(noDelay) fadeOut()).remove();

Thanks in advance, Leo

like image 691
leopic Avatar asked Dec 01 '22 01:12

leopic


2 Answers

There is nothing documented like you want but maybe this will work for you:

$(element).find("." + options.class).fadeOut(noDelay ? 0 : 400).remove();

Why 400, because the default duration for fadeOut is 400 milliseconds. (from documentation)

like image 135
Emre Erkan Avatar answered Dec 04 '22 09:12

Emre Erkan


You could do this with a $.fn.each:

$(element).find("." + options.class).each(function(){
  if (nodelay) {
    $(this).remove();
  }
  else {
    $(this).fadeOut().remove();
  }
});

however it is far less efficient than simply doing what you already are doing.

Edit: here's another way to do it:

$(element).find("." + options.class)[  noDelay ? "detach" : "fadeOut"  ]().remove();

basically, if noDelay is true, it will detach the elements before removing, else, it will fade them out before removing. Should be just as efficient as your code, just on 1 line.

like image 29
Kevin B Avatar answered Dec 04 '22 10:12

Kevin B