Leonardo Lanchas
Leonardo Lanchas

Reputation: 1668

Why zoom in (css) in via jQuery does not work

I know this is maybe a stupid question, but I've researched a lot and do not find why. I have implemented 2 simple jQuery functions for zoom out and zoom in

$("#zoomOutBtn").click(function(){
    var zoom = $("#treeContainer").css("zoom");
    zoom = ((zoom - 0.1) * 100) + "%";
    $("#myDiv").css("zoom", zoom);
  });

  $("#zoomInBtn").click(function(){
    var zoom = $("#treeContainer").css("zoom");
    zoom = ((zoom + 0.1) * 100) + "%";
    $("#myDiv").css("zoom", zoom);
  });

The thing is that zooming out works, but zooming in does not unless run before zoom out.

Upvotes: 1

Views: 44

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074505

+ is overloaded, it means addition when you use it with numbers, but concatenation when you use it where at least one operand is a string. The value you get from css is a string, so zoom + 0.1 will end up appending the characters 0, ., and 1 to the end of the string (e.g., 100%0.1 or whatever), not adding the value 0.1 to it.

To fix it, convert to number first:

zoom = ((parseFloat(zoom) + 0.1) * 100) + "%";

(I used parseFloat there to allow for browsers that include the % in the value that comes back. parseFloat stops at the first invalid character, whereas Number(zoom) or +zoom would result in NaN in that case. Looking at your code, though, you might need a branch specifically to deal with that case, as the math would be different.)

The reason zoom - 0.1 works is that -, unlike +, isn't overloaded; it only has a numeric meaning. So it implicitly coerces its arguments to number, where + won't if either operand is a string.

Upvotes: 3

Related Questions