toggle a flex div with jQuery

The best or better way to handle this is using .toggleClass() and use the hidden class, if you are using bootstrap or just create a new class.

$(function () {
  setInterval(function () {
    $(".flexbox").toggleClass("hidden");
  }, 2000);
});
.flexbox {
  display: flex;
}
.hidden {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="flexbox">FlexBox</div>

This way the display and other properties are always maintained and also there will be a less clutter in the inline CSS generated by jQuery (who cares about that anyway).


From Jquery API -

The display property is saved and restored as needed. If an element has a display value of inline, then is hidden and shown, it will once again be displayed inline.

The same applies with "flex" as would with inline.

So if the elements css is

display: flex;

when toggled it will remain a flexbox when visible.

If you need the element hidden from when the page loads, you may need to use another solution such as the current accepted answer above or a workaround would be to trigger a toggle to hide it with jQuery when the page loads(but that may not be the best practice in my opinion)

Tags:

Jquery