jQuery toggle with Flexbox
July 19, 2022
If you want to toggle a container which is a flexbox, one of the easiest ways, in fact, is to surround your flex container with a standard block container and then use the toggle function on the block container, like so:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<style>
.flex-toggle {display: none}
.flex-box {display: flex; flex-wrap: wrap}
.flex-item {width: 150px; background-color: lightgreen; margin: 5px}
</style>
<body>
<div class="button">Toggle-Button</div>
<div class="flex-toggle">
<div class="flex-box">
<div class="flex-item">Item 1</div>
<div class="flex-item">Item 2</div>
<div class="flex-item">Item 3</div>
</div>
</div>
</body>
<script>
$(document).ready(function(){
$(".button").click(function(){
$(".flex-toggle").toggle();
});
});
</script>
</html>