Reputation: 11394
Is there any way to set an element to display:none
to initially hide it and also specify that, when the element is shown later by JavaScript, it be shown as display:flex
?
Example CSS:
#Container{
display:flex;
display:none;
}
Example jQuery:
$('#Container').show();
Desired behavior: This shows the element as display:flex
without hard-coding a value of flex
in JavaScript.
Note: I am well aware that I can simply set the element to display:flex
with jQuery's CSS method. However, the goal is to separate functionality from presentation, and whether an element is flex or block or inline is not the business of the JavaScript code. JavaScript's job is simply to show or hide it, not to change how the page is presented.
I'm also aware that I could wrap the display:flex
element in a display:none
element and show and hide the outer wrapper. But I'm curious to know if there is a clever way of achieving this without adding extra divs around every pane.
Upvotes: 2
Views: 13099
Reputation: 4294
The best way to do it would be to just add a class to the element instead of show()
. Then this class has the property of display: flex
:
$('div').addClass('flex');
div {
display: none;
width: 100px;
height: 100px;
background: red;
}
div.flex {
display: flex;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div></div>
But if you want to use show()
you can do something like this:
$('div').show();
div {
display: none;
width: 100px;
height: 100px;
background: red;
}
div[style*="display: block"] {
display: flex !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div></div>
When using show()
on the div, it sets the div to display block
, so by using div[style*=display: block]
it selects the div whose style
-attribute contains display: block
. Then we override it by adding display: flex !important
.
Upvotes: 6
Reputation: 12400
One of the most flexible options is to create some utility classes:
.hidden{ display: none; }
.flex{ display: flex; }
Then:
$('#Container').addClass('flex');
Upvotes: 3