Tobias Glaus
Tobias Glaus

Reputation: 3628

Add/Subtract 100% of left attribute doesnt work

So I got an element with the following CSS:

top: 0;
left: 0;
width: 100%;
height: 300px;
border-radius: 0;
box-shadow: none;
transition: all .3s ease-in-out;

On click I am trying to add/subtract 100% from the left property depending on which button is clicked:

$('.next, .prev').click(function() {
   if ($(this).hasClass("next")) {
    $(".element").animate({
      left: '-=100%'
    }, 500);
   }
   else if ($(this).hasClass("prev")) {
    $(".element").animate({
      left: '+=100%'
    }, 500);
   }
});

When I click one of the buttons, it works fine, but on the 2nd press, it jumps to a percentage, which doesn't makes sense to me, i.e. 1002.22%, -802.222, ...

You got a full example here after clicking an element to open the content.

Does anyone know why it's not acting the way I want to?

Upvotes: 2

Views: 75

Answers (1)

danielcooperxyz
danielcooperxyz

Reputation: 999

There is no way to retrieve an elements css value as percentage, so when you try to add or subtract further it is doing this to the pixel value. I found this out when trying to do the subtraction outside of the animate call.

$('.portfolio-next, .portfolio-prev').click(function() {
  var leftVal = parseFloat($(".duplicated .dupAnim").css('left'));
   if ($(this).hasClass("portfolio-next")) {
     leftVal = (leftVal - 100) + '%';

   }
   else if ($(this).hasClass("portfolio-prev")) {
     leftVal = (leftVal + 100) + '%';
   }

    $(".duplicated .dupAnim").animate({
      left: leftVal
    }, 500);
});

The above code does not work, but illustrates a similar issue where the returned value is not a percentage.

In order to solve this you will probably need to keep a count (in a separate attribute or variable) of the number of times it has been added or subtracted. This is a hack and is probably not how I would choose to do it.

Alternatively there is an answer here about calculating the percentage from the pixel value that css() returns.

Upvotes: 1

Related Questions