How to increase the size of box by every click in js

Hi devs. I have to solve this coding challange…
Increase the size of the element by 50 everytime when it was clicked till the element riches 500px. Once it riches 500px decrease the size by 50 it riches its original size.
How can I create logic for this challange
My code

Code here

Here’s a hint:

# javascript
photo.addEventListener('click', (evt) => {
    evt.target.classList.toggle('blue');
});

#css
.blue {
   background: blue;
}

I think once you see how you connect the click event to the object you can do the rest.

Thanks.
But I need actually to use only js. And increse the size by 50px everytime when is clicked on element.
My code works only ones. Thus the code runs only one time. I need to call it again and again untill the size riches 500px…
And then decrease.

I haven’t even read your code yet but here are a few pointers:

  • Change size: offsetHeight or clientHeight attribute (or Weight)
  • On every click [[whatever]]: element.addEventListener('click', (e) => { ... });
  • Increase and decrease: Set/Query the height/width and compare one of those to check if it’s greater than or equal to 500 and react accordingly.
  • Check out event.target as a reference to the origin of an event.

Spoilers - How I would solve it

Don’t read unless you’re absolutely lost.

const box = document.getElementById('photo');
const SIZE_LIMIT = 500;
const INCREMENT = 50;

function sizeChanger(sizeConstraint, increment) {
  let originalSize;
  let direction = 1;

  return function(eventData) {
    const element = eventData.target;
    const [w, h] = [
      element.offsetWidth,
      element.offsetHeight
    ];
    
    if (originalSize === undefined) {
      originalSize = {w, h};
    }
    
    direction = w <= originalSize.w || h <= originalSize.h
      ? 1 : w >= Math.abs(sizeConstraint) || h >= Math.abs(sizeConstraint)
      ? -1 : direction;
    
    console.log(direction, w, h);

    element.style.height = `${h + increment * direction}px`;
    element.style.width = `${w + increment * direction}px`;
  }
}

box.addEventListener('click', sizeChanger(
  SIZE_LIMIT,
  INCREMENT
));

https://codepen.io/luishendrix92/pen/xxwByzv?editors=0010

1 Like

Thanks a lot!!!
This is a really great!