Search code examples
javascriptopacity

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?


Solution

  • 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;