Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to increase opacity in javascript?

I would expect to be able to use

element.style.opacity += 0.1;

or

element.style.opacity = element.style.opacity + 0.1;

but this does not work. The opacity does not change. If I set the opacity to a static value, like

element.style.opacity = 0.5;

it does work. What am I doing wrong?

like image 708
msbg Avatar asked Sep 17 '25 00:09

msbg


1 Answers

element.style.opacity (assuming it is defined at all) will be a String, not a Number.

"0.1" + 0.1 === "0.10.1"

You probably want:

element.style.opacity = parseFloat(element.style.opacity) + 0.1;
like image 51
Quentin Avatar answered Sep 19 '25 16:09

Quentin