Animate margin switching to the left of a div using jQuery?

I try to imitate the code of others, but no luck. How can I get Div1 to switch margin-left: 30% when I click on the DivButton button? Thanks.

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); */ 
+6
source share
3 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/

+3
source

You can use jquery animation.

  $('#DivButton').animate({marginleft: "30%"}, 500); 
+1
source

Try the following:

 $('#DivButton').click(function () { $("#Div1").animate({ marginLeft: '30%' }, 500); }); 

JSFiddle Demo

+1
source

Source: https://habr.com/ru/post/987240/


All Articles