Show div expanding from the middle in jquery
I want to show mine div
when the user generates a trigger. The animation I want to use showing div
is such that it is div
displayed starting from its center and then gaining height, gradually expanding in both directions (up and down). Here is a snippet of what I have tried. div
starts rendering from the left. I want it to start rendering from the middle of its height.
$("#km1").click(function() {
$(".homePopup").animate({
width: "730px",
height: "200px"
}, 800);
})
.homePopup {
position: absolute;
z-index: 100;
width: 400px;
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href="#" id="km1">Know more</a>
<div class="homePopup"></div>
source to share
You can animate margin
to achieve this effect.
Set the initial margin-top
and margin-bottom
half final height
; and margin-left
and margin-right
half of the final width
. Then, as you increase width
and height
, decrease margin
.
$("#km1").click(function() {
$(".homePopup").animate({
width: "730px",
height: "200px",
margin: '0'
}, 800);
})
.homePopup {
position: absolute;
z-index: 100;
width: 0px;
margin: 100px 365px;
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href="#" id="km1">Know more</a>
<div class="homePopup"></div>
source to share
You need to place the element in the middle from the very beginning. I set the left absolute position to 50% and then move the element back -50% of itself to be in the middle.
Check your CSS transform:
http://css-tricks.com/almanac/properties/t/transform/
$("#km1").click(function() {
$(".homePopup").animate({
width: "730px",
height: "200px"
}, 800);
})
.homePopup {
position: absolute;
z-index: 100;
width: 0;
background-color: red;
left: 50%;
transform: translateX(-50%);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href="#" id="km1">Know more</a>
<div class="homePopup"></div>
****** ****** UPDATE
Here is the css to start the animation from the middle of the window height:
.homePopup {
position: absolute;
z-index: 100;
width: 0;
background-color: red;
top: 50%;
transform: translateY(-50%);
}
source to share
I divided the width and height by four and added that on the left and top to get the requested center animation.
$("#km1").click(function() {
$(".homePopup").animate({
width: "730px",
height: "200px",
left: "0px",
top: "0px"
}, 800);
})
.homePopup {
position: absolute;
z-index: 100;
width: 400px;
background-color: red;
left: 182px;
top: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href="#" id="km1">Know more</a>
<div class="homePopup"></div>
source to share