function right() { square.style.left += 50+'px'; } 

How to set not a fixed value in style.left, but add \ remove it?

    1 answer 1

    This property is a string, so before increasing it, you need to convert it to a number, for example using the parseInt function

     function right() { square.style.left = (parseInt(square.style.left,10)+50)+'px'; } 

    Example:

     var square = document.getElementById('square'); square.onclick = function() { right() } function right() { square.style.left = (parseInt(square.style.left, 10) + 50) + 'px'; } 
     #square { position: absolute; background-color: lime; width: 40px; height: 40px; } 
     <div id="square" style="left:0"></div> 

    You should pay attention to the fact that the left property is set in inline styles, otherwise it will be equal to an empty line, and parseInt(square.style.left, 10) will return NaN .

    Another option is to use the function getComputedStyle , which allows you to get the current value of the property, as the default, in the case where the inline property is empty.

     var square = document.getElementById('square'); square.onclick = function() { right() } function right() { square.style.left = (parseInt(square.style.left || getComputedStyle(square)['left'], 10) + 50) + 'px'; } 
     #square { position: absolute; background-color: lime; width: 40px; height: 40px; } 
     <div id="square" style="left:0"></div> 

    • It should make money, but the square element does not move to the left by 50px when the right() function is called. I can not understand why - Sergey Alekseev
    • @SergeyAlekseev, most likely because his position not absolute , or relative , or some other square is possibly selected, or the given link is null and a bunch of errors are written to the console - Grundy
    • This provided - position: absolute Here's the full picture: square.onclick = function() {right()} function right() { square.style.left = (parseInt(square.style.left,10)+50)+'px'; } square.onclick = function() {right()} function right() { square.style.left = (parseInt(square.style.left,10)+50)+'px'; } - Sergey Alekseev
    • @SergeyAlekseev, where is the initial position of this element? - Grundy
    • In html-document this element is the only one in body . #square { position: absolute; width: 100px; height: 100px; background-color: aquamarine; cursor: pointer; } #square { position: absolute; width: 100px; height: 100px; background-color: aquamarine; cursor: pointer; } When the right() function was square.style.left = 50+'px'; , then when you click on an element, it once moved to the right - Sergey Alekseev