Sanjeev K Sanjeev K - 3 months ago 13
CSS Question

Change DIV position on click and animate jQuery

I am trying to move a

DIV
with animation from center to left, and by default
DIV
on click in
jQuery
, where parent div is with
position:relative
, what I was thinking is, onclick the parent
DIV
position will be changed from relative to absolute and then run animate function, but it's not working, it's just shifting from center to left on click, no animation.

Here is the code which I am trying:

$("#bx1 > .column-wrapper-inner > a ").click(function(){
$(".custom-col-md-2").css({position: "absolute"});
$(".column-wrapper").css({position: "absolute"}).animate({left: '50px'}, "slow");
});


Note: I want to change the div position from relative to absolute only on click not by default, as by default elements are in grid.

Can any one please help with this!

UPDATE : Here is the JsFiddle

Thanks in advance.

Answer

How's this (comments in code)

$(document).ready(function() {
  $("#bx1 > .column-wrapper-inner > a ").click(function() {
    var col = $(".custom-col-md-2.column-wrapper-main"); // set the col
    col
      .css({
        'position': 'absolute',
        'left': '50%',
        'margin-left': -(col.outerWidth() / 2) + 'px'   // margin left to move box back into middle
      })                                                // set the css so that it stays centered but has absolute positioning
      .animate({
        'left': '50px',
        'margin-left': '0'
      });                                               // animate to the left

  });
});
.custom-col-md-2 {
  width: 400px;
  height: 300px;
  position: relative;
  margin: 0 auto;
  background: #ccc;
  padding: 10px;
  border: 1px solid #666;
}

.column-wrapper-inner {
  font-size: 16px;
  font-family: arial;
  width: 100%;
  text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="custom-col-md-2 column-wrapper-main">
  <div class="column-wrapper animated infinite slideInUp" id="bx1">
    <div class="column-wrapper-inner">
      <a href="javascript:;">
        <h1>Title goes here</h1>
        <p>&nbsp;</p>
        <p>Desceription goes here.</p>
      </a>
    </div>
  </div>
  <div class="column-wrapper-hov"></div>
</div>