4

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

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

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

You can find a JSFiddle here.

What I can think of is this;

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

..Or something like this by adding a class to the element. But I would prefer not to use an if statement. I wonder if this is possible in a single line of code. Feels like it should be.

Danielle
  • 243
  • 1
  • 3
  • 12

3 Answers3

1

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;
}

then simply toggle no-border-top class, you can see it here

kozettt
  • 26
  • 1
  • 3
0

You can use variables to define toggle effect:

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

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

    currentBorderW = nextBorderW;
});

Here is working jsFiddle.

Barlas Apaydin
  • 7,233
  • 11
  • 55
  • 86
0

Does this do what you want?

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

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

JS Fiddle for this code sample Everything else is the same: your CSS, HTML, etc. I only changed the property border-width to have a value of -= 100px.

I used the -= operator, per the jQuery API docs:

Animated properties can also be relative. If a value is supplied with a leading += or -= sequence of characters, then the target value is computed by adding or subtracting the given number from the current value of the property.

EDIT: To make it slide back in again, see this example on 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);
});
Kenrick Chien
  • 1,036
  • 8
  • 22