The method .toggle()
makes the div
appear/disappear, it is better to use the method .animate()
and encourage the margin-left
for example. The width (width
) could also be an alternative.
So in order to close and open again you can use one flag. A flag is a useful variable for knowing 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 is stored inside a field data
of the element itself.
So every click he will check with a ternary operator if the flag open
has the value true
or false
and as it returns "-250px"
(case open
for true
) or "0px"
(case open
for false
):
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 stores this flag about 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 example (and maybe better) is using a CSS class and 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');
});
Thanks, I think I’ll use this tip and I’ll use an if to give back the initial margin
– blackblather
@blackblather, joined example to open again too
– Sergio
The only problem is that I don’t read too much into the way you used to solve the problem and since I have to defend my project, I might have the misfortune to be asked about it and then I don’t know how to explain it properly, Otherwise, I’m more comfortable if you ask me something. But anyway thank you :)
– blackblather
@blackblather, joined explanation and one more example / variant
– Sergio
Thanks for the explanation, it’s always good to learn new things :)
– blackblather
@blackblather, I added another variant :P
– Sergio
@Zuul thank you :)
– Sergio