pbe
pbe

Reputation: 41

jQuery .css - Relative Percentage Values (+= / -=)

So today I tried to use relative value with jQuery's .css().

$block.css({'margin-left': '-=100%'});

and this happend to div:

<div class="block" style="margin-left: -100px;">

jQuery seems to ignore percentages :( Sooo I did a little research and jQuery docs say:

As of jQuery 1.6, .css() accepts relative values similar to .animate(). Relative values are a string starting with += or -= to increment or decrement the current value.

It has been reported as a bug here. I barely understand what they say doe. I can't figure out how to fix it.

Anybody has an idea how to make this code:

$block.css({'margin-left': '-=100%'});

Do this:

<div class="block" style="margin-left: -100%;">

Then:

<div class="block" style="margin-left: -200%;">

And so on... I now this can be done with .animate() but I want to avoid it, I want to do it with css for hardware acceleration.

Upvotes: 1

Views: 239

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074148

What they're saying there is that it doesn't work right now. The up to date bug report shows a commit, which suggests that it will work in a version coming out soon. The latest milestone it was assigned to was 1.12/2.2, and so it will probably be fixed in v1.12 and v2.2.

In the meantime, three options:

  1. You could use animate with a really short duration (here I'm doing an inline-block and only 25% so we can see the result):

$(".block").animate({'margin-left': '-=25%'}, 10);
.block {
   border: 1px solid black;
   display: inline-block;
}
<div class="block">012345678901234567890123456789</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

  1. Look at the commit and patch your copy of jQuery (or just use the current work-in-progress build).

  2. Measure the element and do it with pixels:

(function() {
        var $block = $(".block");
        $block.css('margin-left', -($block.width() * 0.75));
    })();
.block {
      border: 1px solid black;
      display: inline-block;
    }
<div class="block">012345678901234567890123456789</div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Upvotes: 1

Related Questions