I’m using bootstrap 5, and I would like to fade in/out a particular div element. jQuery has a nifty function called fadeToggle()
for doing this exact thing, so I thought I might use it.
The expected behavior is:
div
element is hidden initially withd-none
class- Click on the button link to toggle fade in/out on the div
However, Bootstrap’s d-none
doesn’t seem to play well with jQuery’s fadeToggle()
, what ends up happening is the div
element pops in without fading in on the first click. Subsequent clicks on the button link will fade correctly because the d-none
class is never added back, so jQuery takes over the hiding/showing of the element. Fading out works fine though.
Here is an example:
<div class="container">
<div class="row">
<div class="col">
<a href="#">Click me</a>
</div>
</div>
<div class="row">
<div class="col">
<div class="one d-none">
1 of 3
</div>
</div>
<div class="col">
<div class="two">
2 of 3
</div>
</div>
<div class="col">
<div class="three">
3 of 3
</div>
</div>
</div>
</div>
jquery script:
$("a").click(function() {
$(".one").fadeToggle(1200, function() {
$(".one").toggleClass("d-none")
});
});
Here is a live example, just refresh the page after the first click to see what I mean about popping in instead of fading incorrectly:
https://codepen.io/iosub/pen/oNdLzgV
How can I get jQuery to play nice with Bootstrap’s d-none
class so that I can fade in/out seamlessly?
As a bonus question, is there a convention for using jquery + bootstrap together? I feel using display properties like d-none
messes with what jquery expects when an element is ‘hidden’ and such, leading to weird behavior like the above. Should jquery just take over in controlling these display properties, or should bootstrap classes be added back in after jquery finishes? (ie, add back d-none
after fadeToggle()
fades out, and remove it when fadeToggle()
fades in. Currently, it just removes the entire d-none
class and hands control over to jquery instead)
3
Answers
Try Following code. Hope It will work.
jQuery acts well with bootstrap so go on with coding. But there are some traps you caught in this one.
bootstrap d-none class applies to element display: none style to an element. But jQuery toggle plays with opacity across 0 (totally transparent and 1 opaque)
so when you use it with the initial state displayed none it shows with no animation because there is no effects with opacity due visibility is initially none so when d-none is removed by callback jQuery apply its rules about opacity due to visibility not affecting its style.
Remember an element displayed none tells the browser I’m here but not show me. An element with opacity 0 tells the browser I’m here but with transparent color.
To reach the desired effect remove d-none and outside of click trigger init element with .hide() Which applies opacity: 0 to element style