The .toggle()
method causes div
to appear / disappear, it is best to use the method .animate()
and animate margin-left
for example. The width (% w / w%) could also be an alternative.
So to be able to close and reopen you can use flag . A flag is a useful variable to know the state of the element.
In this case, I use it to store information about whether it is open or closed. This flag in the first example is a global variable, in the second example it is stored within a% field of% of the element itself.
So with every click it will check with a ternary operator if the flag width
has the value data
or open
and depending on this it returns true
(case false
for "-250px"
) or open
(case true
for "0px"
):
var open = true;
$(document).click(function () {
$("#toggle").animate({
'margin-left': open ? "-250px" : "0px"
}, 500);
open = !open; // mudar a flag para o oposto do que estava usando o operador de negação "!"
});
Another alternative is to have a date field in the element that holds this flag over whether it is open or not:
HTML
<div id="toggle" data-open="true"></div>
JS
$(document).click(function () {
var elemento = $("#toggle");
elemento.animate({
'margin-left': elemento.data('open') ? "-250px" : "0px"
}, 500);
// mudar a flag para o oposto do que estava usando o operador de negação "!"
elemento.data('open', !elemento.data('open'));
});
The third (and perhaps better) example is using a class and CSS transitions:
CSS
#toggle {
width: 300px;
height:300px;
background: #ccc;
-webkit-transition: margin-left 500ms ease;
-moz-transition: margin-left 500ms ease;
-ms-transition: margin-left 500ms ease;
-o-transition: margin-left 500ms ease;
transition: margin-left 500ms ease;
}
.toggle {
margin-left: -250px
}
JS
$(document).click(function() {
var $toggle = $("#toggle");
if ($toggle.hasClass('toggle')) $toggle.removeClass('toggle');
else $toggle.addClass('toggle');
});