Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Animate toggle margin-left of div using jQuery?

I've been trying to mimic others' code but with no luck. How can I get Div1 to toggle margin-left:30% when DivButton is clicked? Thank you.

http://jsfiddle.net/3nc62rec/

HTML

<div id="Div1"></div>
<br><br>
<div id="DivButton"></div>

CSS

#Div1{
    background:blue;
    width:50%;
    height:50px;
    margin-left:0%;
}

#DivButton{
    background:green;
    width:20px;
    height:20px;
}

JS

$('#DivButton').click(function(){                

});


/* 
var toggleWidth = $("#Div1").width() == 365 ? "98%" : "365px"; 
$('#Div1').animate( {'width': toggleWidth}, 300, resize); 
*/

/* 
var toggleMargin = $("#Div1").marginLeft() == 30% ? "10%" : "30%"; 
$('#Div1').animate( {'margin-left': toggleMargin}, 300, resize); 
*/
like image 403
Sherri Avatar asked May 15 '15 00:05

Sherri


2 Answers

var $div1 = $('#Div1')
$('#DivButton').click(function() {
  $div1.toggleClass('isOut')
  var isOut = $div1.hasClass('isOut')
  $div1.animate({marginLeft: isOut ? '30%' : '0'}, 300)
})

http://jsfiddle.net/3nc62rec/2/

like image 114
Farzher Avatar answered Sep 19 '22 15:09

Farzher


You can use a jquery animation.

  $('#DivButton').animate({marginleft: "30%"}, 500);
like image 23
Taylor Avatar answered Sep 20 '22 15:09

Taylor