Jquery animate () toggles without hiding an element

Is there a way to toggle a single CSS property using the animate () function without hiding it? Something like that;

$(".block").animate({ 'border-width': 'toggle' }, 1000);

I cannot use toggleClass (), addClass () or removeClass (). The reason for this is that it has an undesirable effect on the size of the animated element (see JSFiddle).

Here you can find the JSFiddle.

What I can come up with is:

if(parseInt($(".block").css('border-width'))) {
    $(".block").animate({ 'border-width': '0'});
}
else {
    $(".block").animate({ 'border-width': '100px'});
}

.. Or something like this, adding a class to the element. But I would prefer not to use the if statement. I wonder if this is possible in one line of code. It seems like it should be.

+4
source share
3 answers

try using this in your css:

.block1,
.block2 {
    display: inline-block;
    vertical-align: top;
    color: white;
    height: 100%;
    width: 50%;
    transition: all, 1s;
}
.no-border-top {
    border-top-width: 0;
}

no-border-top,

+1

:

var currentBorderW = 0;
$('.block1').on('click', function(){
    var nextBorderW = parseInt($(this).css('border-width'));

    $(this).animate({ 'border-width': currentBorderW + 'px' }, 1000);

    currentBorderW = nextBorderW;
});

jsFiddle.

0

, ?

$('.block1').on('click', function(){
  $(this).animate({ 'border-width': '-=100px' }, 1000);
});

$('.block2').on('click', function(){
  $(this).children().first().show();
  $(this).toggleClass('borderTop', 1000);
});

JS Fiddle : CSS, HTML .. border-width -= 100px.

-= jQuery API docs:

. + = - = , .

. , . JSFiddle

(function(){
  var clickCount=0;
  $('.block1').click(function(){
  if (clickCount%2==0) {
    $(this).animate({ 'border-width': '-=100px' }, 1000);
  }
  else {
   $(this).animate({ 'border-width': '+=100px' }, 1000); 
  }
  clickCount++;
  });
})();

$('.block2').on('click', function(){
  $(this).children().first().show();
  $(this).toggleClass('borderTop', 1000);
});
0

All Articles