Reputation: 314
Sometimes we want to hide/show buttons in a Twitter-bootstrap button group.
<div class="btn-group">
<button id="one" class="btn">one</button>
<button id="two" class="btn">two</button>
<button id="three" class="btn">three</button>
</div>
When we hide button "two" there is no problem
$('#two').hide();
But when we hide the first or the last button, the new first or new last button don't get rounded corners.
Is there a workaround for this, other than just remove and add the buttons?
$('#one').remove();
$('.btn-group').append("<button id='one' class='btn'>one</button>");
When we do this, it is difficult to keep the right button order when you hiding/showing more buttons in a btn-group.
Upvotes: 16
Views: 6485
Reputation: 16659
Because the CSS uses pseudo classes (:last-child and :first-child) you cannot change these classes dynamically using JavaScript, unless you remove/add them from the DOM as you outlined.
What you can do is copy the .btn-group>:last-child and .btn-group>:first-child CSS and apply it dynamically when you show/hide buttons. But note you will have to change this CSS whenever you change your bootstrap theme or look and feel of the buttons. And you will have to keep track of what button is first in the group and what button is last.
Simple example:
<style>
.btn-group > .currently-last {
-webkit-border-top-right-radius: 4px;
-moz-border-radius-topright: 4px;
border-top-right-radius: 4px;
-webkit-border-bottom-right-radius: 4px;
-moz-border-radius-bottomright: 4px;
border-bottom-right-radius: 4px;
}
.btn-group > .currently-first {
margin-left: 0;
-webkit-border-top-left-radius: 4px;
-moz-border-radius-topleft: 4px;
border-top-left-radius: 4px;
-webkit-border-bottom-left-radius: 4px;
-moz-border-radius-bottomleft: 4px;
border-bottom-left-radius: 4px;
}
</style>
<script>
$("#go").click(function() {
$('#three').toggle();
if ($('#three').is(":visible"))
$("#two").removeClass("currently-last");
else
$("#two").addClass("currently-last");
});
</script>
Upvotes: 8
Reputation: 11
have you tried using the :first and :last selectors? I would try that, perhaps reapplying the class after the removal?
Upvotes: 0