Search code examples
javascriptjquerycssexpand

Expand div come back to original position


I make an expandable div and now I want that when I click on the close button, the div come back to the original position is it possible to make it when my close button is inside the div containing my open button? That look not logical but how can I do it ? ( with or without my close button inside the div )

There is my code:

$('.button').click(function(){
$('.intro').hide();
$('.content').animate({width: "500px",}, 500);
    setTimeout(function(){
	$('.content').animate({top: "-400px", marginBottom: "0px", height:"1000px"}, 500);
    },500);
			
    setTimeout(function(){
        $('.button').find('a').show();
        $('.content').find('.full').show();		    
    },1000);
});	
.button{
  margin-top:20px;
  width:50px;
  height:50px;
  cursor:pointer;
  }


.content{
	position:absolute;
	width:250px;
	height:100px;
	overflow:hidden;
	background:red;
	top:50%;
	left:50%;
	margin-left:-230px;
	margin-top:-115px;
}

.button a{
	text-align:left;
	color:grey;
	background:none;
	margin-left:0px;
	display:none;
}

.full{ margin-top:600px;
    display:none;
}
<div class="button"><a class="close_btn"><p>X</p></a>button</div>
<div class="content">
    <div class="intro">intro</div>
    <div class="full">full text lorem ipsum ....
    </div>
</div>


Solution

  • Try this out. I have modified your code a bit. You dont need to use setTimeout because we can make use of the callback function that .animate provides.

    var box = $('.content');
    var position = {
        width: box.width(),
        height: box.height(),
        top: box.css('top'),
        left: box.css('left')
    }
    $('.button').click(function(){
        $('.intro').hide();
        $('.content').animate({
            width: "500px",
            top: "-400px", 
            marginBottom: "0px", 
            height:"1000px"
        }, 500, function(){
             $('.button').find('a').show();
             box.find('.full').show();
        });
    })
    
    $('.close_btn').click(function(e) {
        e.stopPropagation();
        $('.button').find('a').hide();
        box.animate({
            top: position.top,
            height: position.height,
            width: position.width
        });
    
    });
    

    Here is the jsfiddle http://jsfiddle.net/of8znvc5/5/