Martin AJ
Martin AJ

Reputation: 6697

How can I put a condition on the way of jQuery chain?

I have this function:

function startBlinking(el, speed = 100) {
  el.css('display', 'inline').fadeToggle(speed, function() {
    startBlinking(el, speed)
  });
}

I want to add one more parameter to the function to make .css('display', 'inline') part conditional. Something like this:

function startBlinking(el, speed = 100, inlineDisplay = true) {

  if (inlineDisplay){
      el.css('display', 'inline').fadeToggle(speed, function() {
        startBlinking(el, speed)
      });
  } else {
      el.fadeToggle(speed, function() {
        startBlinking(el, speed)
      });
  }
}

But the new version looks ugly. I want to know is there any approach to add a condition in the chain?

Upvotes: 0

Views: 56

Answers (1)

Lorem Ipsum
Lorem Ipsum

Reputation: 357

Get the current display value and add a condition for inlineDisplay parameter. If inlineDisplay is false or undefined the current display value will persist else it will be inline.


function startBlinking(el, speed = 100, inlineDisplay = true) {
    const currentDisplay = el.css('display');
    el.css('display', inlineDisplay ? 'inline' : currentDisplay).fadeToggle(speed, function() {
        startBlinking(el, speed)
      });
}

Upvotes: 1

Related Questions