Let me show you another way, how you can handle this. This solution will work with any number of slides. I hope this helps you. The basic idea is this:
- open a slide
- save this slide on a stack
- continue opening slides or
- close one or more slides
In case of closing it will close all slides up to the selected one. This way you don't need a close all button and you can't get a result where a "nested" slide is still open but its parent is closed.
HTML
To loosen the JavaScript from the markup I've introduced some data-*
-attributes:
data-slide="[name]"
data-id="[name]"
data-direction="[right|up]"
data-slide="[name]" represents a trigger for a slide. In your case:
<div data-slide="slide-1">Toggle Slider</div>
data-id="[name]" identifies a slide. Also information about the direction is stored here:
<div class="cambridge slideout" data-id="slide-1" data-direction="right">
JavaScript
const DELAY = 1000;
var stack = [];
function close(e) {
var value = null;
if (!stack.length) {
return;
}
value = stack.pop();
value.removeClass('active').toggle('slide', {direction: value.data('direction')}, DELAY);
if (!e.length || e.data('id') != value.data('id')) {
setTimeout(function() { close(e); }, DELAY);
}
}
$('[data-slide]').click(function() {
var e = $('[data-id="' + $(this).data('slide') + '"]');
if (!e.hasClass('active')) {
e.addClass('active').toggle('slide', {direction: e.data('direction')}, DELAY);
stack.push(e);
} else {
close(e);
}
});
Advantages
- HTML and JavaScript are more decoupled
- no class- or id-selectors necessary
- no close all function necessary (but you can simply call
close()
to close all slides anyway)
- no ghost slides are visible if you close a "parent" element
Further Improvements
This code can have side effects, when you open a slide while it's closing multiple others. This should be addressed.
jsFiddle Demo
Try before buy
// That's the second question $('#showmap').click(function() { $(".shopping").toggle("slide", { direction: "up" }, 1000, function () { $(".cambridge").toggle("slide", { direction: "right" }, 1000); }); });
\$\endgroup\$