I am currently working on triggering an Offcanvas with JS and making the placement configurable. The issue arises when attempting to dynamically set the offcanvas-end
class to the offcanvas element, as it does not transition smoothly the first time it is triggered. However, on subsequent triggers, the transition works fine. Is there a workaround to make this work seamlessly?
var myOffcanvas = document.getElementById('myOffcanvas')
var btnClicked = function (event) {
myOffcanvas.className += ' offcanvas-end'
var bsOffcanvas = new bootstrap.Offcanvas(myOffcanvas)
bsOffcanvas.show()
}
document.getElementById('myBtn').addEventListener('click', btnClicked)
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="caa8a5a5beb9beb8abba8affe4f9e4f8">[email protected]</a>/dist/js/bootstrap.bundle.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="187a77776c6b6c6a7968582d362b">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet"/>
<div class="offcanvas" tabindex="-1" id="myOffcanvas">My offcanvas</div>
<button type="button" id="myBtn">Open</button>
UPDATE:
Perhaps the following snippet provides a clearer understanding of my objective and why I need to assign the position class in JS rather than HTML - I aim to dynamically open the offcanvas at different positions based on the trigger element.
var myOffcanvas = document.getElementById('myOffcanvas')
var bsOffcanvas = null
var openLeftBtnClicked = function(event) {
myOffcanvas.className = 'offcanvas offcanvas-start'
if (bsOffcanvas) {
bsOffcanvas.dispose()
}
bsOffcanvas = new bootstrap.Offcanvas(myOffcanvas)
bsOffcanvas.show()
}
var openRightBtnClicked = function(event) {
myOffcanvas.className = 'offcanvas offcanvas-end'
if (bsOffcanvas) {
bsOffcanvas.dispose()
}
bsOffcanvas = new bootstrap.Offcanvas(myOffcanvas)
bsOffcanvas.show()
}
document.getElementById('openLeftBtn').addEventListener('click', openLeftBtnClicked)
document.getElementById('openRightBtn').addEventListener('click', openRightBtnClicked)
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ef8d80809b9c9b9d8e9fafdac1dfc1dd">[email protected]</a>/dist/js/bootstrap.bundle.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="97f5f8f8e3e4e3e5f6e7d7a2b9a7b9a5">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" />
<div tabindex="-1" id="myOffcanvas"></div>
<button type="button" id="openLeftBtn">Open left</button>
<button type="button" id="openRightBtn">Open right</button>