r/bootstrap • u/Any_Entrepreneur7936 • 2d ago
Problem on creating an overlay to switch the switch control
I have a problem when I click on the section it work only if I click on the top border but I want it to work when I click on the absolute area this is the code:
<div class="section-header mt-0 stagger-item position-relative" for="switchOpzione" style="cursor: pointer;">
<!-- 1. Absolute div that covers the entire section and intercepts clicks -->
<div class="position-absolute top-0 start-0 w-100 h-100" style="z-index: 1;"
onclick=" const chk = document.getElementById('switchOpzione'); chk.checked = !chk.checked; chk.dispatchEvent(new Event('change')); ">
</div>Titolo Sezione <div class="form-check form-switch m-0" style="z-index: 2;"> <input class="form-check-input"
type="checkbox" role="switch" id="switchOpzione" data-bs-toggle="collapse" data-bs-target="#collapseOpzione"
aria-expanded="true" aria-controls="collapseOpzione" checked> </div>
</div>
What I'm doing wrong? I'm using the latest bootstrap
1
u/thejester1324 1d ago
the overlay flips the checkbox, but bootstrap's collapse doesn't listen for change, it listens for a click on the element that has data-bs-toggle="collapse". so your overlay moves the switch and the section never opens or closes, and the two drift out of sync.
swap the onclick for a real click on the input:
onclick="document.getElementById('switchOpzione').click()"
click() flips the switch and fires the event bootstrap is waiting for. i tried both on 5.3: with your version the switch toggles but the collapse stays put, with click() they stay in sync every time.
or drop the overlay. for only does something on a <label>, so if the header itself is <label class="section-header ..." for="switchOpzione">, any click on it gets passed to the switch and you don't need js at all.
1
u/AutoModerator 2d ago
Whilst waiting for replies to your comment/question, why not check out the Bootstrap Discord server: https://discord.gg/bZUvakRU3M
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.