Xander
Xander

Reputation: 1011

How to increase a css value, rather than concatenate it?

I'm currently using this line:

$(this).css("z-index", z + 10);

The set z-index value is 1200.

edit: This is my variable z = $(this).css("z-index");

When debugging in the developer console I noticed that my z-index value was '120010' rather than the expected '1210'.

How can I change the above line to increase the value by 10, rather than concatenating the value to the end.

(Also am I using that word right? I'm not 100% sure)

Upvotes: 1

Views: 61

Answers (1)

Dryden Long
Dryden Long

Reputation: 10180

You probably need to use the parseInt() function on your z variable. Something like this should work:

z = parseInt($(this).css("z-index"));
$(this).css("z-index", z + 10);

One thing to be careful about with this though, is that z-index can have a value that is not a number, for example auto If you run parseInt() on an element that's z-index is auto, it will break.

In order to combat this, I would recommend using zIndex() (part of jQuery UI) instead of css() like so:

z = $(this).zIndex();
$(this).css("z-index", z + 10);

This of course means you have to use jQueryUI, but if you are already using it, I'd recommend this approach.

EDIT: It looks like zIndex() has been removed from jQuery UI, so just stick to my first suggestion. http://jqueryui.com/upgrade-guide/1.12/#removed-zindex

Upvotes: 1

Related Questions