Skip to content
Advertisement

JavaScript grow and shrink “ball” object

started to learn a bit javascript and I ran into a mission to get a “ball” bigger and bigger when I am cliking it( the ball starts from 100 and grow by 50 each click). so when it’s getting too 400 its should shrink its size by 50 till the ball gets again to 100 and then he grow.

so thats the code:

      function onBall2Click() {
        var ball2 = document.querySelector('.ball2');
        if(ball2Size === 400) {
            ball2Size -= 50;
        } else if(ball2Size) {
            ball2Size += 50;
        }
      
       
      
        ball2.innerText = ball2Size;
        ball2.style.width = ball2Size;
        ball2.style.height = ball2Size;
    }

ball2Size defined to 100.

now the ball is getting to 400 when I click again it is getting to 350 but then it getting to 400 again since 350 isnt === to 400. I am frustrated I tried to play with it like an hour and got stucked thats why I posted it here.. would like if someone could give me an useful solution. thank you!

Advertisement

Answer

The code behave like this because once you shrink it first time, it’s not 400 anymore, so it goes into ELSE and grow it again.

To achieve that you need to have a variable in outside scope of your function that will hold information if the ball is growing or not.

Ideally that should not be defined in the Global scope (as it would pollute global scope that is anti-pattern), however I can’t see the rest of your code so I don’t know into what closure the isGrowing variable should be placed.

   var ball2SizeStep = 50;

   function onBall2Click() {
        var ball2 = document.querySelector('.ball2');
        


        if(ball2Size === 400) {
            ball2SizeStep = -50;
        } else if(ball2Size === 100) {
            ball2SizeStep = 50;
        }
      
        ball2Size += ball2SizeStep;
        
        ball2.innerText = ball2Size;
        ball2.style.width = ball2Size;
        ball2.style.height = ball2Size;
    }
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement