0

How to use .toggle() method but not for show and hide purposes?

For example, when I click on a certain div I would like to animate it's position
$(div).animate({"left":"+=50px"}); and then on the second click to return the div on the same position $(div).animate({"left":"-=50px"}).

I know there is other solution but I would like to achieve this with .toggle() without hiding an showing the div. Any ideas?

Maistrenko Vitalii
  • 994
  • 1
  • 8
  • 16
N. Eli
  • 1

2 Answers2

1

$("#myDiv").toggle(function() {
    $(this).stop().animate({
       left:"+=50"
    }, 500);
}, function() {
    $(this).stop().animate({
        left:"-=50"
    }, 500);
});
#myDiv{
background-color:black;
width:100px;
height:100px;
position:absolute;
left:50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>

<div id="myDiv"></div>

hope this answer your question. However, jQuery 1.9 and newer do not allow this feature.

Wils
  • 1,178
  • 8
  • 24
  • Thank you for the answer. But I don't like to use Class with CSS. I would like to achieve this with poor jQuery. Any ideas ??? – N. Eli Mar 22 '18 at 02:51
0

there is no toggle function using click since 1.9 . But you can still doing this using two ways:

for more explaination

$(function(){
  //basic method
  var clicked = false;
  $('#mydiv1').click(function(){
    if(clicked){
      clicked = false;
      $(this).animate({"left":"+=50px"});
    }else{
      clicked=true;
      $(this).animate({"left":"-=50px"});
    }
  });
  
  //create new function like old built-in function
  $.fn.clickToggle = function(func1, func2) {
        var funcs = [func1, func2];
        this.data('toggleclicked', 0);
        this.click(function() {
            var data = $(this).data();
            var tc = data.toggleclicked;
            $.proxy(funcs[tc], this)();
            data.toggleclicked = (tc + 1) % 2;
        });
        return this;
    };
  
  $('#mydiv2').clickToggle(function(){
      $(this).animate({"left":"+=50px"});
    }, function(){
      $(this).animate({"left":"-=50px"});
  });
  
});
#mydiv1{
  background-color: yellow;
  width: 50px;
  height: 50px;
  position: absolute;
  left: 100px;
}

#mydiv2{
background-color: blue;
  width: 50px;
  height: 50px;
  position: absolute;
  left: 200px;
  top: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div id="mydiv1"></div>
  <div id="mydiv2"></div>
  
</div>
plonknimbuzz
  • 2,594
  • 2
  • 19
  • 31