javascripthtmlcsssetattributegetattribute

Problems while adding a number to width attribute


My code should keep making my image wider for 1px every 200ms after a button is clicked, but i feel like it's adding 20-30 instead.

Here's my code <img id="testimage" src="wall.png" width="50" height="25"/>

setInterval( function() {var im = document.getElementById("testimage");
    var newWidth = (im.getAttribute("width") ? im.getAttribute("width") : 0) + 1; //here
    im.setAttribute("width", newWidth); console.log(im.getAttribute)}, 200)
}

Solution

  • Convert the width from a string to a number to perform addition rather than string concatenation. This can be done with the unary plus operator.

    var newWidth = (im.getAttribute("width") ? +im.getAttribute("width") : 0) + 1;
    

    Alternatively, directly update the width property, which is a number.

    let im = document.getElementById("testimage");
    setInterval(function() {
        ++im.width;
    }, 200);
    <img id="testimage" src="https://via.placeholder.com/50x50" width="50" height="50"/>