Image opacity doesn't increase in html


I want to make an image gradually emerge using opacity property, only to find that its opacity only increases 0.1 instead of 1. It seems that it only increases one time, but I set condition that it continue to increase until opacity reaches 1.

So I use another same image, whose opacity is 1. Then decrease opacity until opacity reaches 0. However, it finally disappears as expected.

It turns out that opacity can only change from 1 to 0, but can’t change from 0 to 1?

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">

<img class="view1" src="">
<img class="view2" src="">
    let myView = document.querySelector('.view1'); = 1;
    function changeOpacity() { -= 0.01;
        if ( <= 0) {
    let timer = setInterval(changeOpacity, 10);

    let secondView = document.querySelector('.view2'); = 0;
    function changeAnotherOpacity() { += 0.1;
        if ( >= 1) {
    let anotherTimer = setInterval(changeAnotherOpacity, 10);

IDE might warn that opacity is a string, but it doesn’t matter. The result is same even if write = "1"


The Issue lies within the += and -= operators to Set the value. As -= only applies for Mathematical operations, += can also concatenate strings. In the first the String gets converted to a Number to use the -= operator, therefore reducing the number value by 0.1 works as expected. But the += operator will concatenate the value as a String, because the value of .style.opacity is a String and therefore concatenating the 0.1 as a String resulting in "00.1", which is somewhat weird but will be corrected to "0.1". But the 2nd Iteration would resolve in "0.10.1" as the new value, which cant be corrected or even converted to a valid Number.

Hence you should adjust your code for compensating this behaviour:

function changeAnotherOpacity() { = Number( + 0.1;
  if ( >= 1) {

Answered By – IISkullsII

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published