Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiply CSS property values with jQuery using *=

Tags:

jquery

*= is a valid javascript assignment operator. Why can't I use it to animate property values? The code below will not work. All I want to do is double the width and height.

$('div.box').animate({
    'width' : '*=2',
    'height' : '*=2',
}, 'slow');
like image 642
wetjosh Avatar asked Mar 22 '23 03:03

wetjosh


2 Answers

This doesn't work simply because nobody has implemented it yet. If you want to do so (and make the worldjQuery a bit better), just take a look at the "Contribut to jQuery".page.

To solve your problem for now: you have to do the calculation on your own - something like the following (not tested, but you should get the idea):

For a single element:

var element = $('#animate');
element .animate({
  'width' : element.width()*2,
  'height' : element.height()*2,
}, 'slow');

For multiple elements:

$('.animate').each(function(){
  var element = $(this);
  element .animate({
    'width' : element.width()*2,
    'height' : element.height()*2,
  }, 'slow');
});
like image 75
oezi Avatar answered May 01 '23 13:05

oezi


Fundamentally, because you're trying to pass it an expression literal, rather than the results of an expression. jQuery has no handling within itself to understand the difference. And why should it? jQuery shouldn't have to have an entire Javascript interpreter within it. That's serious bloat.

The closest you're going to get is:

var divbox = $('div.box');
divbox.animate({ 
    width: (divbox.width() * 2) + 'px', 
    height: (divbox.height() * 2) + 'px'
});
like image 21
Elf Sternberg Avatar answered May 01 '23 12:05

Elf Sternberg