Solution 1 :

In order to animate the left and top you’ll need an initial value, which you don’t have. You can add them upon click and then set the new values by changing the class.

Note that I added the new values in the style so we also need to add !important to the class rule so it will override the inline style.

function expand(){
  // get the element
  var box = document.getElementsByClassName("box")[0];
  
  // set top and left properties
  box.style.setProperty("left", box.offsetLeft + "px");
  box.style.setProperty("top", box.offsetTop + "px");
  box.style.setProperty("position", "absolute");
  
  // now change the class for the animation will work
  box.className = "fullscreen";
}
.box {
  width: 80px;
  height: 80px;
  background: red;
  cursor: pointer;
  transition: 1s ease-in-out;
  margin: 0 auto;
  margin-top: 100px;
}

.fullscreen {
  width: 100vw;
  height: 100vh;
  position: absolute;
  top: 0 !important;
  left: 0 !important;
  background: red;
  transition: 1s ease-in-out;
}
<div class="box" onClick="expand()"></div>

Problem :

How do I animate a to expand to fit the screen upon clicking. I do not want to give a position in the initial state. Div should be able to be used dynamically within the screen.

.box {
  width: 80px;
  height: 80px;
  background: red;
  cursor: pointer;
  transition: 1s ease-in-out;
}

.fullscreen {
  width: 100vw;
  height: 100vh;
  position: absolute;
  top:0;
  left:0;
  background: red;
  transition: 1s ease-in-out;
}

Codepen demo of my code

Comments

Comment posted by Manikandan2811

can u plz send ur code or add ur code in codepen?

Comment posted by Ref

So what is your question ?, How to add class

Comment posted by Kevin

Your Question is a bit unclear. Please Clarify your need and put the code that you have done to get help from others.

Comment posted by Ahmet Kuşlular

I want to make fullScreen when a box is clicked. However, the box can be used anywhere in the screen. so its location is unclear. So I can’t give a position.

Comment posted by minimal reproducible example

You are required to post a

Comment posted by Ahmet Kuşlular

the problem is not in the click script, but in animation. I guess you didn’t understand my question.

Comment posted by Itay Gal

I fixed my answer, if I undetstood right, you want the animation to start from the current place and not from “0,0”

Comment posted by Ahmet Kuşlular

exactly, you understood my question but the animation does not work properly. Going directly to the top.

Comment posted by Itay Gal

Related to my example – I added margin-top as initial value, and it works

Comment posted by codepen

codepen

By