I have implemented Bootstrap's Buttons plugin to toggle the state of a custom checkbox. When the button is toggled on, a hidden element should appear at the top of the page and then the page should scroll to the top. Similarly, when the button is toggled off, the element should disappear and the page should scroll to the top.
Although the hidden element toggles correctly with the button, the scrolling feature does not work as intended.
I attempted changing the data-toggle attribute from 'buttons' to 'button', which made the scroll function properly but caused the button to not visually toggle, rendering this solution ineffective.
Setting an onchange event for the checkbox itself also did not result in successful scrolling.
It seems that Bootstrap's onclick event function may be interfering with the execution of my own event handling function. I need to investigate this further to understand the issue.
Utilizing a timeout for the window.scrollTo() function allows the scrolling to happen. However, I am curious about why this workaround is necessary and if there is a way to achieve the desired functionality without relying on a timeout.
<body>
<div class="container">
<div>
<h3>Toggle Header and Scroll To Top</h3><hr />
<h1 id="displayMe" class="d-none">Display Me</h1>
<div style="height: 100vh;"></div>
<div class="btn-group-toggle btn btn-success custom-control custom-switch" data-toggle="buttons" id="myButton">
<input type="checkbox" class="custom-control-input" id="myCheckbox">
<label class="custom-control-label" for="myCheckbox">Toggle and Scroll</label>
</div>
</div>
</div>
<script src="assets/jquery/jquery.min.js"></script>
<script src="assets/twitter-bootstrap/js/bootstrap.min.js"></script>
<script>
$(document).ready(function () {
$("#myButton").on("click", toggleAndScroll);
});
function toggleAndScroll() {
$('#displayMe').toggleClass('d-none');
window.scrollTo(0, 0);
}
</script>
</body>
https://jsfiddle.net/ews9q50v/
(Uncomment the setTimeout lines to see it working)