Home > database >  How to increase width and height on click of a button
How to increase width and height on click of a button

Time:01-29

I need to increase height actually to increase bottom and top of div each for 25px also left and right side each for 25px.I don't now is that even possible.

So this is just example but it is similar to my code:

function increaseDiv() {
var myDiv = document.querySelector(".box")
var currWidth = myDiv.clientWidth;
myDiv.style.width = currWidth   100   "px";
}
.box {
width: 300px;
height: 200px;
position: absolute;
left: 100px;
background: black;
}
<div ></div>
<button onclick="increaseDiv()">Click</button>

Here is demo https://jsfiddle.net/SutonJ/0pdwm39a/14/

CodePudding user response:

The problem is that position of your div are related to left side and this is why it looks like you increase only the right side; try to add positioning with transform by center or make it by flex(align-items justify-content)

.box {
  width: 300px;
  height: 200px;
  left: 50%;
  position: absolute;
  top: 50%;
  transform: translate(-50%, -50%);
  background: black;
}

CodePudding user response:

What about CSS scale?

That will keep the actual position of the element and expand it in all directions, unless you specify a transform-origin value.

Edited with an ever growing effect...

let myDiv = document.querySelector(".box");
let orgiSize = myDiv.getBoundingClientRect().width;
let increments = 0;

function increaseDiv() {
  increments  = 50; // That is 25px on both sides...

  // Make the math here
  var percentage = Math.floor((orgiSize   increments) / orgiSize * 100) / 100

  console.log(percentage);
  myDiv.style.transform = `scale(${percentage})`; // That is a percentage value
}
.box {
  width: 300px;
  height: 200px;
  position: absolute;
  left: 100px;
  background: black;
}


/* for the demo */

button {
  position: absolute;
  z-index: 9999;
}
<div ></div>
<button onclick="increaseDiv()">Click</button>

CodePudding user response:

If I am understanding you correctly, I think if you changed

var currWidth = myDiv.clientWidth;
myDiv.style.width = currWidth   100   "px";

to

var currWidth = myDiv.getBoundingClientRect().width;
myDiv.style.width = currWidth   50   "px";

and also added

var currHeight = myDiv.getBoundingClientRect().height;
myDiv.style.height = currHeight   50   "px";

I also noticed that your div is using absolute positioning, so you may also need to offset the left and top according to the size change. If you are getting an issue with the actual position when the size changes let me know.

  •  Tags:  
  • Related