I am trying to toggle a div with jQuery, the twist is my div is a flex container.
Is there a jquery function equivalent to .toggle()
that would toggle between display:none;
and display:flex;
instead of the standard that goes between display:none
and display:block;
jQuery toggle() Method The toggle() method toggles between hide() and show() for the selected elements. This method checks the selected elements for visibility. show() is run if an element is hidden.
In this case, only current container must show and hide. The class container's first div child is initally displayed and the second div child is hidden/ display:none. upon button click, the second div child is displayed, the display:none is change to display:block.
To display or hide a <div> by a <button> click, you can add the onclick event listener to the <button> element. The onclick listener for the button will have a function that will change the display attribute of the <div> from the default value (which is block ) to none .
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)
You can add a normal div (block) before the flex div and toggle it. This will do the trick you need.
Try the example! Thank you :)
function toggleAreaData(){
jQuery( "#toggler" ).toggle( "#toggler" );
}
<html>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Toggle a flex with toggle()!
<br>
<br>
<!-- toggle container block -->
<div id="toggler">
<div style="display:flex;">
MY FLEX TOGGLE DATA<br>
MY FLEX TOGGLE DATA
</div>
</div>
<br>
<!-- toggle button -->
<button onclick="toggleAreaData()">PRESS TO TOGGLE</button>
<br>
<br>
So just use a div block inside a div flex :)
</html>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With